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
342
Power of Four
Easy
<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p> <p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 16 <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 5 <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> n = 1 <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you solve it without loops/recursion?
Bit Manipulation; Recursion; Math
TypeScript
function isPowerOfFour(n: number): boolean { return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0; }
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
C
#define max(a, b) (((a) > (b)) ? (a) : (b)) int integerBreak(int n) { int* f = (int*) malloc((n + 1) * sizeof(int)); f[1] = 1; for (int i = 2; i <= n; ++i) { f[i] = 0; for (int j = 1; j < i; ++j) { f[i] = max(f[i], max(f[i - j] * j, (i - j) * j)); } } return f[n]; }
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
C++
class Solution { public: int integerBreak(int n) { vector<int> f(n + 1); f[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 1; j < i; ++j) { f[i] = max({f[i], f[i - j] * j, (i - j) * j}); } } return f[n]; } };
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
C#
public class Solution { public int IntegerBreak(int n) { int[] f = new int[n + 1]; f[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 1; j < i; ++j) { f[i] = Math.Max(Math.Max(f[i], f[i - j] * j), (i - j) * j); } } return f[n]; } }
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
Go
func integerBreak(n int) int { f := make([]int, n+1) f[1] = 1 for i := 2; i <= n; i++ { for j := 1; j < i; j++ { f[i] = max(max(f[i], f[i-j]*j), (i-j)*j) } } return f[n] }
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
Java
class Solution { public int integerBreak(int n) { int[] f = new int[n + 1]; f[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 1; j < i; ++j) { f[i] = Math.max(Math.max(f[i], f[i - j] * j), (i - j) * j); } } return f[n]; } }
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
JavaScript
/** * @param {number} n * @return {number} */ var integerBreak = function (n) { const f = Array(n + 1).fill(1); for (let i = 2; i <= n; ++i) { for (let j = 1; j < i; ++j) { f[i] = Math.max(f[i], f[i - j] * j, (i - j) * j); } } return f[n]; };
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
Python
class Solution: def integerBreak(self, n: int) -> int: f = [1] * (n + 1) for i in range(2, n + 1): for j in range(1, i): f[i] = max(f[i], f[i - j] * j, (i - j) * j) return f[n]
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
Rust
impl Solution { pub fn integer_break(n: i32) -> i32 { let n = n as usize; let mut f = vec![0; n + 1]; f[1] = 1; for i in 2..=n { for j in 1..i { f[i] = f[i].max(f[i - j] * j).max((i - j) * j); } } f[n] as i32 } }
343
Integer Break
Medium
<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p> <p>Return <em>the maximum product you can get</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 1 <strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 10 <strong>Output:</strong> 36 <strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 58</code></li> </ul>
Math; Dynamic Programming
TypeScript
function integerBreak(n: number): number { const f = Array(n + 1).fill(1); for (let i = 3; i <= n; i++) { for (let j = 1; j < i; j++) { f[i] = Math.max(f[i], j * (i - j), j * f[i - j]); } } return f[n]; }
344
Reverse String
Easy
<p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p> <p>You must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> with <code>O(1)</code> extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["h","e","l","l","o"] <strong>Output:</strong> ["o","l","l","e","h"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["H","a","n","n","a","h"] <strong>Output:</strong> ["h","a","n","n","a","H"] </pre> <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[i]</code> is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>.</li> </ul>
Two Pointers; String
C++
class Solution { public: void reverseString(vector<char>& s) { for (int i = 0, j = s.size() - 1; i < j;) { swap(s[i++], s[j--]); } } };
344
Reverse String
Easy
<p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p> <p>You must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> with <code>O(1)</code> extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["h","e","l","l","o"] <strong>Output:</strong> ["o","l","l","e","h"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["H","a","n","n","a","h"] <strong>Output:</strong> ["h","a","n","n","a","H"] </pre> <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[i]</code> is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>.</li> </ul>
Two Pointers; String
Go
func reverseString(s []byte) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } }
344
Reverse String
Easy
<p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p> <p>You must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> with <code>O(1)</code> extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["h","e","l","l","o"] <strong>Output:</strong> ["o","l","l","e","h"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["H","a","n","n","a","h"] <strong>Output:</strong> ["h","a","n","n","a","H"] </pre> <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[i]</code> is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>.</li> </ul>
Two Pointers; String
Java
class Solution { public void reverseString(char[] s) { for (int i = 0, j = s.length - 1; i < j; ++i, --j) { char t = s[i]; s[i] = s[j]; s[j] = t; } } }
344
Reverse String
Easy
<p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p> <p>You must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> with <code>O(1)</code> extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["h","e","l","l","o"] <strong>Output:</strong> ["o","l","l","e","h"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["H","a","n","n","a","h"] <strong>Output:</strong> ["h","a","n","n","a","H"] </pre> <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[i]</code> is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>.</li> </ul>
Two Pointers; String
JavaScript
/** * @param {character[]} s * @return {void} Do not return anything, modify s in-place instead. */ var reverseString = function (s) { for (let i = 0, j = s.length - 1; i < j; ++i, --j) { [s[i], s[j]] = [s[j], s[i]]; } };
344
Reverse String
Easy
<p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p> <p>You must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> with <code>O(1)</code> extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["h","e","l","l","o"] <strong>Output:</strong> ["o","l","l","e","h"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["H","a","n","n","a","h"] <strong>Output:</strong> ["h","a","n","n","a","H"] </pre> <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[i]</code> is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>.</li> </ul>
Two Pointers; String
Python
class Solution: def reverseString(self, s: List[str]) -> None: i, j = 0, len(s) - 1 while i < j: s[i], s[j] = s[j], s[i] i, j = i + 1, j - 1
344
Reverse String
Easy
<p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p> <p>You must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> with <code>O(1)</code> extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["h","e","l","l","o"] <strong>Output:</strong> ["o","l","l","e","h"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["H","a","n","n","a","h"] <strong>Output:</strong> ["h","a","n","n","a","H"] </pre> <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[i]</code> is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>.</li> </ul>
Two Pointers; String
Rust
impl Solution { pub fn reverse_string(s: &mut Vec<char>) { let mut i = 0; let mut j = s.len() - 1; while i < j { s.swap(i, j); i += 1; j -= 1; } } }
344
Reverse String
Easy
<p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p> <p>You must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> with <code>O(1)</code> extra memory.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = ["h","e","l","l","o"] <strong>Output:</strong> ["o","l","l","e","h"] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = ["H","a","n","n","a","h"] <strong>Output:</strong> ["h","a","n","n","a","H"] </pre> <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[i]</code> is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>.</li> </ul>
Two Pointers; String
TypeScript
/** Do not return anything, modify s in-place instead. */ function reverseString(s: string[]): void { for (let i = 0, j = s.length - 1; i < j; ++i, --j) { [s[i], s[j]] = [s[j], s[i]]; } }
345
Reverse Vowels of a String
Easy
<p>Given a string <code>s</code>, reverse only all the vowels in the string and return it.</p> <p>The vowels are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>, and they can appear in both lower and upper cases, more than once.</p> <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;IceCreAm&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;AceCreIm&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The vowels in <code>s</code> are <code>[&#39;I&#39;, &#39;e&#39;, &#39;e&#39;, &#39;A&#39;]</code>. On reversing the vowels, s becomes <code>&quot;AceCreIm&quot;</code>.</p> </div> <p><strong class="example">Example 2:</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">&quot;leotcede&quot;</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consist of <strong>printable ASCII</strong> characters.</li> </ul>
Two Pointers; String
C++
class Solution { public: string reverseVowels(string s) { bool vowels[128]; memset(vowels, false, sizeof(vowels)); for (char c : "aeiouAEIOU") { vowels[c] = true; } int i = 0, j = s.size() - 1; while (i < j) { while (i < j && !vowels[s[i]]) { ++i; } while (i < j && !vowels[s[j]]) { --j; } if (i < j) { swap(s[i++], s[j--]); } } return s; } };
345
Reverse Vowels of a String
Easy
<p>Given a string <code>s</code>, reverse only all the vowels in the string and return it.</p> <p>The vowels are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>, and they can appear in both lower and upper cases, more than once.</p> <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;IceCreAm&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;AceCreIm&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The vowels in <code>s</code> are <code>[&#39;I&#39;, &#39;e&#39;, &#39;e&#39;, &#39;A&#39;]</code>. On reversing the vowels, s becomes <code>&quot;AceCreIm&quot;</code>.</p> </div> <p><strong class="example">Example 2:</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">&quot;leotcede&quot;</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consist of <strong>printable ASCII</strong> characters.</li> </ul>
Two Pointers; String
Go
func reverseVowels(s string) string { vowels := [128]bool{} for _, c := range "aeiouAEIOU" { vowels[c] = true } cs := []byte(s) i, j := 0, len(cs)-1 for i < j { for i < j && !vowels[cs[i]] { i++ } for i < j && !vowels[cs[j]] { j-- } if i < j { cs[i], cs[j] = cs[j], cs[i] i, j = i+1, j-1 } } return string(cs) }
345
Reverse Vowels of a String
Easy
<p>Given a string <code>s</code>, reverse only all the vowels in the string and return it.</p> <p>The vowels are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>, and they can appear in both lower and upper cases, more than once.</p> <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;IceCreAm&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;AceCreIm&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The vowels in <code>s</code> are <code>[&#39;I&#39;, &#39;e&#39;, &#39;e&#39;, &#39;A&#39;]</code>. On reversing the vowels, s becomes <code>&quot;AceCreIm&quot;</code>.</p> </div> <p><strong class="example">Example 2:</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">&quot;leotcede&quot;</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consist of <strong>printable ASCII</strong> characters.</li> </ul>
Two Pointers; String
Java
class Solution { public String reverseVowels(String s) { boolean[] vowels = new boolean[128]; for (char c : "aeiouAEIOU".toCharArray()) { vowels[c] = true; } char[] cs = s.toCharArray(); int i = 0, j = cs.length - 1; while (i < j) { while (i < j && !vowels[cs[i]]) { ++i; } while (i < j && !vowels[cs[j]]) { --j; } if (i < j) { char t = cs[i]; cs[i] = cs[j]; cs[j] = t; ++i; --j; } } return String.valueOf(cs); } }
345
Reverse Vowels of a String
Easy
<p>Given a string <code>s</code>, reverse only all the vowels in the string and return it.</p> <p>The vowels are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>, and they can appear in both lower and upper cases, more than once.</p> <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;IceCreAm&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;AceCreIm&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The vowels in <code>s</code> are <code>[&#39;I&#39;, &#39;e&#39;, &#39;e&#39;, &#39;A&#39;]</code>. On reversing the vowels, s becomes <code>&quot;AceCreIm&quot;</code>.</p> </div> <p><strong class="example">Example 2:</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">&quot;leotcede&quot;</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consist of <strong>printable ASCII</strong> characters.</li> </ul>
Two Pointers; String
Python
class Solution: def reverseVowels(self, s: str) -> str: vowels = "aeiouAEIOU" i, j = 0, len(s) - 1 cs = list(s) while i < j: while i < j and cs[i] not in vowels: i += 1 while i < j and cs[j] not in vowels: j -= 1 if i < j: cs[i], cs[j] = cs[j], cs[i] i, j = i + 1, j - 1 return "".join(cs)
345
Reverse Vowels of a String
Easy
<p>Given a string <code>s</code>, reverse only all the vowels in the string and return it.</p> <p>The vowels are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>, and they can appear in both lower and upper cases, more than once.</p> <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;IceCreAm&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;AceCreIm&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The vowels in <code>s</code> are <code>[&#39;I&#39;, &#39;e&#39;, &#39;e&#39;, &#39;A&#39;]</code>. On reversing the vowels, s becomes <code>&quot;AceCreIm&quot;</code>.</p> </div> <p><strong class="example">Example 2:</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">&quot;leotcede&quot;</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consist of <strong>printable ASCII</strong> characters.</li> </ul>
Two Pointers; String
Rust
impl Solution { pub fn reverse_vowels(s: String) -> String { let vowel = String::from("aeiouAEIOU"); let mut data: Vec<char> = s.chars().collect(); let (mut i, mut j) = (0, s.len() - 1); while i < j { while i < j && !vowel.contains(data[i]) { i += 1; } while i < j && !vowel.contains(data[j]) { j -= 1; } if i < j { data.swap(i, j); i += 1; j -= 1; } } data.iter().collect() } }
345
Reverse Vowels of a String
Easy
<p>Given a string <code>s</code>, reverse only all the vowels in the string and return it.</p> <p>The vowels are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>, and they can appear in both lower and upper cases, more than once.</p> <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;IceCreAm&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;AceCreIm&quot;</span></p> <p><strong>Explanation:</strong></p> <p>The vowels in <code>s</code> are <code>[&#39;I&#39;, &#39;e&#39;, &#39;e&#39;, &#39;A&#39;]</code>. On reversing the vowels, s becomes <code>&quot;AceCreIm&quot;</code>.</p> </div> <p><strong class="example">Example 2:</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">&quot;leotcede&quot;</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consist of <strong>printable ASCII</strong> characters.</li> </ul>
Two Pointers; String
TypeScript
function reverseVowels(s: string): string { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); const cs = s.split(''); for (let i = 0, j = cs.length - 1; i < j; ++i, --j) { while (i < j && !vowels.has(cs[i].toLowerCase())) { ++i; } while (i < j && !vowels.has(cs[j].toLowerCase())) { --j; } [cs[i], cs[j]] = [cs[j], cs[i]]; } return cs.join(''); }
346
Moving Average from Data Stream
Easy
<p>Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.</p> <p>Implement the&nbsp;<code>MovingAverage</code> class:</p> <ul> <li><code>MovingAverage(int size)</code> Initializes&nbsp;the object with the size of the window <code>size</code>.</li> <li><code>double next(int val)</code> Returns the moving average of the last <code>size</code> values of the stream.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MovingAverage&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;] [[3], [1], [10], [3], [5]] <strong>Output</strong> [null, 1.0, 5.5, 4.66667, 6.0] <strong>Explanation</strong> MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= size &lt;= 1000</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>next</code>.</li> </ul>
Design; Queue; Array; Data Stream
C++
class MovingAverage { public: MovingAverage(int size) { data.resize(size); } double next(int val) { int i = cnt % data.size(); s += val - data[i]; data[i] = val; ++cnt; return s * 1.0 / min(cnt, (int) data.size()); } private: int s = 0; int cnt = 0; vector<int> data; }; /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage* obj = new MovingAverage(size); * double param_1 = obj->next(val); */
346
Moving Average from Data Stream
Easy
<p>Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.</p> <p>Implement the&nbsp;<code>MovingAverage</code> class:</p> <ul> <li><code>MovingAverage(int size)</code> Initializes&nbsp;the object with the size of the window <code>size</code>.</li> <li><code>double next(int val)</code> Returns the moving average of the last <code>size</code> values of the stream.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MovingAverage&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;] [[3], [1], [10], [3], [5]] <strong>Output</strong> [null, 1.0, 5.5, 4.66667, 6.0] <strong>Explanation</strong> MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= size &lt;= 1000</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>next</code>.</li> </ul>
Design; Queue; Array; Data Stream
Go
type MovingAverage struct { s int cnt int data []int } func Constructor(size int) MovingAverage { return MovingAverage{ data: make([]int, size), } } func (this *MovingAverage) Next(val int) float64 { i := this.cnt % len(this.data) this.s += val - this.data[i] this.data[i] = val this.cnt++ return float64(this.s) / float64(min(this.cnt, len(this.data))) } /** * Your MovingAverage object will be instantiated and called as such: * obj := Constructor(size); * param_1 := obj.Next(val); */
346
Moving Average from Data Stream
Easy
<p>Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.</p> <p>Implement the&nbsp;<code>MovingAverage</code> class:</p> <ul> <li><code>MovingAverage(int size)</code> Initializes&nbsp;the object with the size of the window <code>size</code>.</li> <li><code>double next(int val)</code> Returns the moving average of the last <code>size</code> values of the stream.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MovingAverage&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;] [[3], [1], [10], [3], [5]] <strong>Output</strong> [null, 1.0, 5.5, 4.66667, 6.0] <strong>Explanation</strong> MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= size &lt;= 1000</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>next</code>.</li> </ul>
Design; Queue; Array; Data Stream
Java
class MovingAverage { private int s; private int cnt; private int[] data; public MovingAverage(int size) { data = new int[size]; } public double next(int val) { int i = cnt % data.length; s += val - data[i]; data[i] = val; ++cnt; return s * 1.0 / Math.min(cnt, data.length); } } /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */
346
Moving Average from Data Stream
Easy
<p>Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.</p> <p>Implement the&nbsp;<code>MovingAverage</code> class:</p> <ul> <li><code>MovingAverage(int size)</code> Initializes&nbsp;the object with the size of the window <code>size</code>.</li> <li><code>double next(int val)</code> Returns the moving average of the last <code>size</code> values of the stream.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MovingAverage&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;] [[3], [1], [10], [3], [5]] <strong>Output</strong> [null, 1.0, 5.5, 4.66667, 6.0] <strong>Explanation</strong> MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= size &lt;= 1000</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>next</code>.</li> </ul>
Design; Queue; Array; Data Stream
Python
class MovingAverage: def __init__(self, size: int): self.s = 0 self.data = [0] * size self.cnt = 0 def next(self, val: int) -> float: i = self.cnt % len(self.data) self.s += val - self.data[i] self.data[i] = val self.cnt += 1 return self.s / min(self.cnt, len(self.data)) # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val)
346
Moving Average from Data Stream
Easy
<p>Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.</p> <p>Implement the&nbsp;<code>MovingAverage</code> class:</p> <ul> <li><code>MovingAverage(int size)</code> Initializes&nbsp;the object with the size of the window <code>size</code>.</li> <li><code>double next(int val)</code> Returns the moving average of the last <code>size</code> values of the stream.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;MovingAverage&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;, &quot;next&quot;] [[3], [1], [10], [3], [5]] <strong>Output</strong> [null, 1.0, 5.5, 4.66667, 6.0] <strong>Explanation</strong> MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= size &lt;= 1000</code></li> <li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>next</code>.</li> </ul>
Design; Queue; Array; Data Stream
TypeScript
class MovingAverage { private s: number = 0; private cnt: number = 0; private data: number[]; constructor(size: number) { this.data = Array(size).fill(0); } next(val: number): number { const i = this.cnt % this.data.length; this.s += val - this.data[i]; this.data[i] = val; this.cnt++; return this.s / Math.min(this.cnt, this.data.length); } } /** * Your MovingAverage object will be instantiated and called as such: * var obj = new MovingAverage(size) * var param_1 = obj.next(val) */
347
Top K Frequent Elements
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,2,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,1,2,3,1,3,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>k</code> is in the range <code>[1, the number of unique elements in the array]</code>.</li> <li>It is <strong>guaranteed</strong> that the answer is <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Your algorithm&#39;s time complexity must be better than <code>O(n log n)</code>, where n is the array&#39;s size.</p>
Array; Hash Table; Divide and Conquer; Bucket Sort; Counting; Quickselect; Sorting; Heap (Priority Queue)
C++
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> cnt; using pii = pair<int, int>; for (int x : nums) { ++cnt[x]; } priority_queue<pii, vector<pii>, greater<pii>> pq; for (auto& [x, c] : cnt) { pq.push({c, x}); if (pq.size() > k) { pq.pop(); } } vector<int> ans; while (!pq.empty()) { ans.push_back(pq.top().second); pq.pop(); } return ans; } };
347
Top K Frequent Elements
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,2,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,1,2,3,1,3,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>k</code> is in the range <code>[1, the number of unique elements in the array]</code>.</li> <li>It is <strong>guaranteed</strong> that the answer is <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Your algorithm&#39;s time complexity must be better than <code>O(n log n)</code>, where n is the array&#39;s size.</p>
Array; Hash Table; Divide and Conquer; Bucket Sort; Counting; Quickselect; Sorting; Heap (Priority Queue)
Go
func topKFrequent(nums []int, k int) []int { cnt := map[int]int{} for _, x := range nums { cnt[x]++ } pq := hp{} for x, c := range cnt { heap.Push(&pq, pair{x, c}) if pq.Len() > k { heap.Pop(&pq) } } ans := make([]int, k) for i := 0; i < k; i++ { ans[i] = heap.Pop(&pq).(pair).v } return ans } type pair struct{ v, cnt int } type hp []pair func (h hp) Len() int { return len(h) } func (h hp) Less(i, j int) bool { return h[i].cnt < h[j].cnt } func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
347
Top K Frequent Elements
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,2,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,1,2,3,1,3,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>k</code> is in the range <code>[1, the number of unique elements in the array]</code>.</li> <li>It is <strong>guaranteed</strong> that the answer is <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Your algorithm&#39;s time complexity must be better than <code>O(n log n)</code>, where n is the array&#39;s size.</p>
Array; Hash Table; Divide and Conquer; Bucket Sort; Counting; Quickselect; Sorting; Heap (Priority Queue)
Java
class Solution { public int[] topKFrequent(int[] nums, int k) { Map<Integer, Integer> cnt = new HashMap<>(); for (int x : nums) { cnt.merge(x, 1, Integer::sum); } PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue)); for (var e : cnt.entrySet()) { pq.offer(e); if (pq.size() > k) { pq.poll(); } } return pq.stream().mapToInt(Map.Entry::getKey).toArray(); } }
347
Top K Frequent Elements
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,2,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,1,2,3,1,3,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>k</code> is in the range <code>[1, the number of unique elements in the array]</code>.</li> <li>It is <strong>guaranteed</strong> that the answer is <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Your algorithm&#39;s time complexity must be better than <code>O(n log n)</code>, where n is the array&#39;s size.</p>
Array; Hash Table; Divide and Conquer; Bucket Sort; Counting; Quickselect; Sorting; Heap (Priority Queue)
Python
class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: cnt = Counter(nums) return [x for x, _ in cnt.most_common(k)]
347
Top K Frequent Elements
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,2,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,1,2,3,1,3,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>k</code> is in the range <code>[1, the number of unique elements in the array]</code>.</li> <li>It is <strong>guaranteed</strong> that the answer is <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Your algorithm&#39;s time complexity must be better than <code>O(n log n)</code>, where n is the array&#39;s size.</p>
Array; Hash Table; Divide and Conquer; Bucket Sort; Counting; Quickselect; Sorting; Heap (Priority Queue)
Rust
use std::cmp::Reverse; use std::collections::{BinaryHeap, HashMap}; impl Solution { pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> { let mut cnt = HashMap::new(); for x in nums { *cnt.entry(x).or_insert(0) += 1; } let mut pq = BinaryHeap::with_capacity(k as usize); for (&x, &c) in cnt.iter() { pq.push(Reverse((c, x))); if pq.len() > k as usize { pq.pop(); } } pq.into_iter().map(|Reverse((_, x))| x).collect() } }
347
Top K Frequent Elements
Medium
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,1,2,2,3], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">[1]</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,2,1,2,3,1,3,2], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2]</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> <li><code>k</code> is in the range <code>[1, the number of unique elements in the array]</code>.</li> <li>It is <strong>guaranteed</strong> that the answer is <strong>unique</strong>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Your algorithm&#39;s time complexity must be better than <code>O(n log n)</code>, where n is the array&#39;s size.</p>
Array; Hash Table; Divide and Conquer; Bucket Sort; Counting; Quickselect; Sorting; Heap (Priority Queue)
TypeScript
function topKFrequent(nums: number[], k: number): number[] { const cnt = new Map<number, number>(); for (const x of nums) { cnt.set(x, (cnt.get(x) ?? 0) + 1); } const pq = new MinPriorityQueue(); for (const [x, c] of cnt) { pq.enqueue(x, c); if (pq.size() > k) { pq.dequeue(); } } return pq.toArray().map(x => x.element); }
348
Design Tic-Tac-Toe
Medium
<p>Assume the following rules are for the tic-tac-toe game on an <code>n x n</code> board between two players:</p> <ol> <li>A move is guaranteed to be valid and is placed on an empty block.</li> <li>Once a winning condition is reached, no more moves are allowed.</li> <li>A player who succeeds in placing <code>n</code> of their marks in a horizontal, vertical, or diagonal row wins the game.</li> </ol> <p>Implement the <code>TicTacToe</code> class:</p> <ul> <li><code>TicTacToe(int n)</code> Initializes the object the size of the board <code>n</code>.</li> <li><code>int move(int row, int col, int player)</code> Indicates that the player with id <code>player</code> plays at the cell <code>(row, col)</code> of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return <ul> <li><code>0</code> if there is <strong>no winner</strong> after the move,</li> <li><code>1</code> if <strong>player 1</strong> is the winner after the move, or</li> <li><code>2</code> if <strong>player 2</strong> is the winner after the move.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TicTacToe&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]] <strong>Output</strong> [null, 0, 0, 0, 0, 0, 0, 1] <strong>Explanation</strong> TicTacToe ticTacToe = new TicTacToe(3); Assume that player 1 is &quot;X&quot; and player 2 is &quot;O&quot; in the board. ticTacToe.move(0, 0, 1); // return 0 (no one wins) |X| | | | | | | // Player 1 makes a move at (0, 0). | | | | ticTacToe.move(0, 2, 2); // return 0 (no one wins) |X| |O| | | | | // Player 2 makes a move at (0, 2). | | | | ticTacToe.move(2, 2, 1); // return 0 (no one wins) |X| |O| | | | | // Player 1 makes a move at (2, 2). | | |X| ticTacToe.move(1, 1, 2); // return 0 (no one wins) |X| |O| | |O| | // Player 2 makes a move at (1, 1). | | |X| ticTacToe.move(2, 0, 1); // return 0 (no one wins) |X| |O| | |O| | // Player 1 makes a move at (2, 0). |X| |X| ticTacToe.move(1, 0, 2); // return 0 (no one wins) |X| |O| |O|O| | // Player 2 makes a move at (1, 0). |X| |X| ticTacToe.move(2, 1, 1); // return 1&nbsp;(player 1 wins) |X| |O| |O|O| | // Player 1 makes a move at (2, 1). |X|X|X| </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li>player is <code>1</code> or <code>2</code>.</li> <li><code>0 &lt;= row, col &lt; n</code></li> <li><code>(row, col)</code> are <strong>unique</strong> for each different call to <code>move</code>.</li> <li>At most <code>n<sup>2</sup></code> calls will be made to <code>move</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code> per <code>move()</code> operation?</p>
Design; Array; Hash Table; Matrix; Simulation
C++
class TicTacToe { private: int n; vector<vector<int>> cnt; public: TicTacToe(int n) : n(n) , cnt(2, vector<int>((n << 1) + 2, 0)) { } int move(int row, int col, int player) { vector<int>& cur = cnt[player - 1]; ++cur[row]; ++cur[n + col]; if (row == col) { ++cur[n << 1]; } if (row + col == n - 1) { ++cur[n << 1 | 1]; } if (cur[row] == n || cur[n + col] == n || cur[n << 1] == n || cur[n << 1 | 1] == n) { return player; } return 0; } }; /** * Your TicTacToe object will be instantiated and called as such: * TicTacToe* obj = new TicTacToe(n); * int param_1 = obj->move(row,col,player); */
348
Design Tic-Tac-Toe
Medium
<p>Assume the following rules are for the tic-tac-toe game on an <code>n x n</code> board between two players:</p> <ol> <li>A move is guaranteed to be valid and is placed on an empty block.</li> <li>Once a winning condition is reached, no more moves are allowed.</li> <li>A player who succeeds in placing <code>n</code> of their marks in a horizontal, vertical, or diagonal row wins the game.</li> </ol> <p>Implement the <code>TicTacToe</code> class:</p> <ul> <li><code>TicTacToe(int n)</code> Initializes the object the size of the board <code>n</code>.</li> <li><code>int move(int row, int col, int player)</code> Indicates that the player with id <code>player</code> plays at the cell <code>(row, col)</code> of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return <ul> <li><code>0</code> if there is <strong>no winner</strong> after the move,</li> <li><code>1</code> if <strong>player 1</strong> is the winner after the move, or</li> <li><code>2</code> if <strong>player 2</strong> is the winner after the move.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TicTacToe&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]] <strong>Output</strong> [null, 0, 0, 0, 0, 0, 0, 1] <strong>Explanation</strong> TicTacToe ticTacToe = new TicTacToe(3); Assume that player 1 is &quot;X&quot; and player 2 is &quot;O&quot; in the board. ticTacToe.move(0, 0, 1); // return 0 (no one wins) |X| | | | | | | // Player 1 makes a move at (0, 0). | | | | ticTacToe.move(0, 2, 2); // return 0 (no one wins) |X| |O| | | | | // Player 2 makes a move at (0, 2). | | | | ticTacToe.move(2, 2, 1); // return 0 (no one wins) |X| |O| | | | | // Player 1 makes a move at (2, 2). | | |X| ticTacToe.move(1, 1, 2); // return 0 (no one wins) |X| |O| | |O| | // Player 2 makes a move at (1, 1). | | |X| ticTacToe.move(2, 0, 1); // return 0 (no one wins) |X| |O| | |O| | // Player 1 makes a move at (2, 0). |X| |X| ticTacToe.move(1, 0, 2); // return 0 (no one wins) |X| |O| |O|O| | // Player 2 makes a move at (1, 0). |X| |X| ticTacToe.move(2, 1, 1); // return 1&nbsp;(player 1 wins) |X| |O| |O|O| | // Player 1 makes a move at (2, 1). |X|X|X| </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li>player is <code>1</code> or <code>2</code>.</li> <li><code>0 &lt;= row, col &lt; n</code></li> <li><code>(row, col)</code> are <strong>unique</strong> for each different call to <code>move</code>.</li> <li>At most <code>n<sup>2</sup></code> calls will be made to <code>move</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code> per <code>move()</code> operation?</p>
Design; Array; Hash Table; Matrix; Simulation
Go
type TicTacToe struct { n int cnt [][]int } func Constructor(n int) TicTacToe { cnt := make([][]int, 2) for i := range cnt { cnt[i] = make([]int, (n<<1)+2) } return TicTacToe{n, cnt} } func (this *TicTacToe) Move(row int, col int, player int) int { cur := this.cnt[player-1] cur[row]++ cur[this.n+col]++ if row == col { cur[this.n<<1]++ } if row+col == this.n-1 { cur[this.n<<1|1]++ } if cur[row] == this.n || cur[this.n+col] == this.n || cur[this.n<<1] == this.n || cur[this.n<<1|1] == this.n { return player } return 0 } /** * Your TicTacToe object will be instantiated and called as such: * obj := Constructor(n); * param_1 := obj.Move(row,col,player); */
348
Design Tic-Tac-Toe
Medium
<p>Assume the following rules are for the tic-tac-toe game on an <code>n x n</code> board between two players:</p> <ol> <li>A move is guaranteed to be valid and is placed on an empty block.</li> <li>Once a winning condition is reached, no more moves are allowed.</li> <li>A player who succeeds in placing <code>n</code> of their marks in a horizontal, vertical, or diagonal row wins the game.</li> </ol> <p>Implement the <code>TicTacToe</code> class:</p> <ul> <li><code>TicTacToe(int n)</code> Initializes the object the size of the board <code>n</code>.</li> <li><code>int move(int row, int col, int player)</code> Indicates that the player with id <code>player</code> plays at the cell <code>(row, col)</code> of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return <ul> <li><code>0</code> if there is <strong>no winner</strong> after the move,</li> <li><code>1</code> if <strong>player 1</strong> is the winner after the move, or</li> <li><code>2</code> if <strong>player 2</strong> is the winner after the move.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TicTacToe&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]] <strong>Output</strong> [null, 0, 0, 0, 0, 0, 0, 1] <strong>Explanation</strong> TicTacToe ticTacToe = new TicTacToe(3); Assume that player 1 is &quot;X&quot; and player 2 is &quot;O&quot; in the board. ticTacToe.move(0, 0, 1); // return 0 (no one wins) |X| | | | | | | // Player 1 makes a move at (0, 0). | | | | ticTacToe.move(0, 2, 2); // return 0 (no one wins) |X| |O| | | | | // Player 2 makes a move at (0, 2). | | | | ticTacToe.move(2, 2, 1); // return 0 (no one wins) |X| |O| | | | | // Player 1 makes a move at (2, 2). | | |X| ticTacToe.move(1, 1, 2); // return 0 (no one wins) |X| |O| | |O| | // Player 2 makes a move at (1, 1). | | |X| ticTacToe.move(2, 0, 1); // return 0 (no one wins) |X| |O| | |O| | // Player 1 makes a move at (2, 0). |X| |X| ticTacToe.move(1, 0, 2); // return 0 (no one wins) |X| |O| |O|O| | // Player 2 makes a move at (1, 0). |X| |X| ticTacToe.move(2, 1, 1); // return 1&nbsp;(player 1 wins) |X| |O| |O|O| | // Player 1 makes a move at (2, 1). |X|X|X| </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li>player is <code>1</code> or <code>2</code>.</li> <li><code>0 &lt;= row, col &lt; n</code></li> <li><code>(row, col)</code> are <strong>unique</strong> for each different call to <code>move</code>.</li> <li>At most <code>n<sup>2</sup></code> calls will be made to <code>move</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code> per <code>move()</code> operation?</p>
Design; Array; Hash Table; Matrix; Simulation
Java
class TicTacToe { private int n; private int[][] cnt; public TicTacToe(int n) { this.n = n; cnt = new int[2][(n << 1) + 2]; } public int move(int row, int col, int player) { int[] cur = cnt[player - 1]; ++cur[row]; ++cur[n + col]; if (row == col) { ++cur[n << 1]; } if (row + col == n - 1) { ++cur[n << 1 | 1]; } if (cur[row] == n || cur[n + col] == n || cur[n << 1] == n || cur[n << 1 | 1] == n) { return player; } return 0; } } /** * Your TicTacToe object will be instantiated and called as such: * TicTacToe obj = new TicTacToe(n); * int param_1 = obj.move(row,col,player); */
348
Design Tic-Tac-Toe
Medium
<p>Assume the following rules are for the tic-tac-toe game on an <code>n x n</code> board between two players:</p> <ol> <li>A move is guaranteed to be valid and is placed on an empty block.</li> <li>Once a winning condition is reached, no more moves are allowed.</li> <li>A player who succeeds in placing <code>n</code> of their marks in a horizontal, vertical, or diagonal row wins the game.</li> </ol> <p>Implement the <code>TicTacToe</code> class:</p> <ul> <li><code>TicTacToe(int n)</code> Initializes the object the size of the board <code>n</code>.</li> <li><code>int move(int row, int col, int player)</code> Indicates that the player with id <code>player</code> plays at the cell <code>(row, col)</code> of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return <ul> <li><code>0</code> if there is <strong>no winner</strong> after the move,</li> <li><code>1</code> if <strong>player 1</strong> is the winner after the move, or</li> <li><code>2</code> if <strong>player 2</strong> is the winner after the move.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TicTacToe&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]] <strong>Output</strong> [null, 0, 0, 0, 0, 0, 0, 1] <strong>Explanation</strong> TicTacToe ticTacToe = new TicTacToe(3); Assume that player 1 is &quot;X&quot; and player 2 is &quot;O&quot; in the board. ticTacToe.move(0, 0, 1); // return 0 (no one wins) |X| | | | | | | // Player 1 makes a move at (0, 0). | | | | ticTacToe.move(0, 2, 2); // return 0 (no one wins) |X| |O| | | | | // Player 2 makes a move at (0, 2). | | | | ticTacToe.move(2, 2, 1); // return 0 (no one wins) |X| |O| | | | | // Player 1 makes a move at (2, 2). | | |X| ticTacToe.move(1, 1, 2); // return 0 (no one wins) |X| |O| | |O| | // Player 2 makes a move at (1, 1). | | |X| ticTacToe.move(2, 0, 1); // return 0 (no one wins) |X| |O| | |O| | // Player 1 makes a move at (2, 0). |X| |X| ticTacToe.move(1, 0, 2); // return 0 (no one wins) |X| |O| |O|O| | // Player 2 makes a move at (1, 0). |X| |X| ticTacToe.move(2, 1, 1); // return 1&nbsp;(player 1 wins) |X| |O| |O|O| | // Player 1 makes a move at (2, 1). |X|X|X| </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li>player is <code>1</code> or <code>2</code>.</li> <li><code>0 &lt;= row, col &lt; n</code></li> <li><code>(row, col)</code> are <strong>unique</strong> for each different call to <code>move</code>.</li> <li>At most <code>n<sup>2</sup></code> calls will be made to <code>move</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code> per <code>move()</code> operation?</p>
Design; Array; Hash Table; Matrix; Simulation
Python
class TicTacToe: def __init__(self, n: int): self.n = n self.cnt = [defaultdict(int), defaultdict(int)] def move(self, row: int, col: int, player: int) -> int: cur = self.cnt[player - 1] n = self.n cur[row] += 1 cur[n + col] += 1 if row == col: cur[n << 1] += 1 if row + col == n - 1: cur[n << 1 | 1] += 1 if any(cur[i] == n for i in (row, n + col, n << 1, n << 1 | 1)): return player return 0 # Your TicTacToe object will be instantiated and called as such: # obj = TicTacToe(n) # param_1 = obj.move(row,col,player)
348
Design Tic-Tac-Toe
Medium
<p>Assume the following rules are for the tic-tac-toe game on an <code>n x n</code> board between two players:</p> <ol> <li>A move is guaranteed to be valid and is placed on an empty block.</li> <li>Once a winning condition is reached, no more moves are allowed.</li> <li>A player who succeeds in placing <code>n</code> of their marks in a horizontal, vertical, or diagonal row wins the game.</li> </ol> <p>Implement the <code>TicTacToe</code> class:</p> <ul> <li><code>TicTacToe(int n)</code> Initializes the object the size of the board <code>n</code>.</li> <li><code>int move(int row, int col, int player)</code> Indicates that the player with id <code>player</code> plays at the cell <code>(row, col)</code> of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return <ul> <li><code>0</code> if there is <strong>no winner</strong> after the move,</li> <li><code>1</code> if <strong>player 1</strong> is the winner after the move, or</li> <li><code>2</code> if <strong>player 2</strong> is the winner after the move.</li> </ul> </li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TicTacToe&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]] <strong>Output</strong> [null, 0, 0, 0, 0, 0, 0, 1] <strong>Explanation</strong> TicTacToe ticTacToe = new TicTacToe(3); Assume that player 1 is &quot;X&quot; and player 2 is &quot;O&quot; in the board. ticTacToe.move(0, 0, 1); // return 0 (no one wins) |X| | | | | | | // Player 1 makes a move at (0, 0). | | | | ticTacToe.move(0, 2, 2); // return 0 (no one wins) |X| |O| | | | | // Player 2 makes a move at (0, 2). | | | | ticTacToe.move(2, 2, 1); // return 0 (no one wins) |X| |O| | | | | // Player 1 makes a move at (2, 2). | | |X| ticTacToe.move(1, 1, 2); // return 0 (no one wins) |X| |O| | |O| | // Player 2 makes a move at (1, 1). | | |X| ticTacToe.move(2, 0, 1); // return 0 (no one wins) |X| |O| | |O| | // Player 1 makes a move at (2, 0). |X| |X| ticTacToe.move(1, 0, 2); // return 0 (no one wins) |X| |O| |O|O| | // Player 2 makes a move at (1, 0). |X| |X| ticTacToe.move(2, 1, 1); // return 1&nbsp;(player 1 wins) |X| |O| |O|O| | // Player 1 makes a move at (2, 1). |X|X|X| </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 100</code></li> <li>player is <code>1</code> or <code>2</code>.</li> <li><code>0 &lt;= row, col &lt; n</code></li> <li><code>(row, col)</code> are <strong>unique</strong> for each different call to <code>move</code>.</li> <li>At most <code>n<sup>2</sup></code> calls will be made to <code>move</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow-up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code> per <code>move()</code> operation?</p>
Design; Array; Hash Table; Matrix; Simulation
TypeScript
class TicTacToe { private n: number; private cnt: number[][]; constructor(n: number) { this.n = n; this.cnt = [Array((n << 1) + 2).fill(0), Array((n << 1) + 2).fill(0)]; } move(row: number, col: number, player: number): number { const cur = this.cnt[player - 1]; cur[row]++; cur[this.n + col]++; if (row === col) { cur[this.n << 1]++; } if (row + col === this.n - 1) { cur[(this.n << 1) | 1]++; } if ( cur[row] === this.n || cur[this.n + col] === this.n || cur[this.n << 1] === this.n || cur[(this.n << 1) | 1] === this.n ) { return player; } return 0; } } /** * Your TicTacToe object will be instantiated and called as such: * var obj = new TicTacToe(n) * var param_1 = obj.move(row,col,player) */
349
Intersection of Two Arrays
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword="array-intersection">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [9,4] <strong>Explanation:</strong> [4,9] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
C++
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { bool s[1001]; memset(s, false, sizeof(s)); for (int x : nums1) { s[x] = true; } vector<int> ans; for (int x : nums2) { if (s[x]) { ans.push_back(x); s[x] = false; } } return ans; } };
349
Intersection of Two Arrays
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword="array-intersection">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [9,4] <strong>Explanation:</strong> [4,9] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
C#
public class Solution { public int[] Intersection(int[] nums1, int[] nums2) { HashSet<int> s1 = new HashSet<int>(nums1); HashSet<int> s2 = new HashSet<int>(nums2); s1.IntersectWith(s2); int[] ans = new int[s1.Count]; s1.CopyTo(ans); return ans; } }
349
Intersection of Two Arrays
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword="array-intersection">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [9,4] <strong>Explanation:</strong> [4,9] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Go
func intersection(nums1 []int, nums2 []int) (ans []int) { s := [1001]bool{} for _, x := range nums1 { s[x] = true } for _, x := range nums2 { if s[x] { ans = append(ans, x) s[x] = false } } return }
349
Intersection of Two Arrays
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword="array-intersection">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [9,4] <strong>Explanation:</strong> [4,9] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Java
class Solution { public int[] intersection(int[] nums1, int[] nums2) { boolean[] s = new boolean[1001]; for (int x : nums1) { s[x] = true; } List<Integer> ans = new ArrayList<>(); for (int x : nums2) { if (s[x]) { ans.add(x); s[x] = false; } } return ans.stream().mapToInt(Integer::intValue).toArray(); } }
349
Intersection of Two Arrays
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword="array-intersection">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [9,4] <strong>Explanation:</strong> [4,9] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
JavaScript
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersection = function (nums1, nums2) { const s = new Set(nums1); return [...new Set(nums2.filter(x => s.has(x)))]; };
349
Intersection of Two Arrays
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword="array-intersection">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [9,4] <strong>Explanation:</strong> [4,9] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
PHP
class Solution { /** * @param Integer[] $nums1 * @param Integer[] $nums2 * @return Integer[] */ function intersection($nums1, $nums2) { $s1 = array_unique($nums1); $s2 = array_unique($nums2); $ans = array_intersect($s1, $s2); return array_values($ans); } }
349
Intersection of Two Arrays
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword="array-intersection">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [9,4] <strong>Explanation:</strong> [4,9] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Python
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return list(set(nums1) & set(nums2))
349
Intersection of Two Arrays
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword="array-intersection">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [9,4] <strong>Explanation:</strong> [4,9] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
TypeScript
function intersection(nums1: number[], nums2: number[]): number[] { const s = new Set(nums1); return [...new Set(nums2.filter(x => s.has(x)))]; }
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
C++
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> cnt; for (int x : nums1) { ++cnt[x]; } vector<int> ans; for (int x : nums2) { if (cnt[x]-- > 0) { ans.push_back(x); } } return ans; } };
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
C#
public class Solution { public int[] Intersect(int[] nums1, int[] nums2) { Dictionary<int, int> cnt = new Dictionary<int, int>(); foreach (int x in nums1) { if (cnt.ContainsKey(x)) { cnt[x]++; } else { cnt[x] = 1; } } List<int> ans = new List<int>(); foreach (int x in nums2) { if (cnt.ContainsKey(x) && cnt[x] > 0) { ans.Add(x); cnt[x]--; } } return ans.ToArray(); } }
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Go
func intersect(nums1 []int, nums2 []int) (ans []int) { cnt := map[int]int{} for _, x := range nums1 { cnt[x]++ } for _, x := range nums2 { if cnt[x] > 0 { ans = append(ans, x) cnt[x]-- } } return }
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Java
class Solution { public int[] intersect(int[] nums1, int[] nums2) { int[] cnt = new int[1001]; for (int x : nums1) { ++cnt[x]; } List<Integer> ans = new ArrayList<>(); for (int x : nums2) { if (cnt[x]-- > 0) { ans.add(x); } } return ans.stream().mapToInt(Integer::intValue).toArray(); } }
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
JavaScript
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersect = function (nums1, nums2) { const cnt = {}; for (const x of nums1) { cnt[x] = (cnt[x] || 0) + 1; } const ans = []; for (const x of nums2) { if (cnt[x]-- > 0) { ans.push(x); } } return ans; };
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
PHP
class Solution { /** * @param Integer[] $nums1 * @param Integer[] $nums2 * @return Integer[] */ function intersect($nums1, $nums2) { $cnt = []; foreach ($nums1 as $x) { if (isset($cnt[$x])) { $cnt[$x]++; } else { $cnt[$x] = 1; } } $ans = []; foreach ($nums2 as $x) { if (isset($cnt[$x]) && $cnt[$x] > 0) { $ans[] = $x; $cnt[$x]--; } } return $ans; } }
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Python
class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: cnt = Counter(nums1) ans = [] for x in nums2: if cnt[x]: ans.append(x) cnt[x] -= 1 return ans
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
Rust
use std::collections::HashMap; impl Solution { pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> { let mut cnt = HashMap::new(); for &x in &nums1 { *cnt.entry(x).or_insert(0) += 1; } let mut ans = Vec::new(); for &x in &nums2 { if let Some(count) = cnt.get_mut(&x) { if *count > 0 { ans.push(x); *count -= 1; } } } ans } }
350
Intersection of Two Arrays II
Easy
<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2] <strong>Output:</strong> [2,2] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4] <strong>Output:</strong> [4,9] <strong>Explanation:</strong> [9,4] is also accepted. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li> <li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the given array is already sorted? How would you optimize your algorithm?</li> <li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li> <li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li> </ul>
Array; Hash Table; Two Pointers; Binary Search; Sorting
TypeScript
function intersect(nums1: number[], nums2: number[]): number[] { const cnt: Record<number, number> = {}; for (const x of nums1) { cnt[x] = (cnt[x] || 0) + 1; } const ans: number[] = []; for (const x of nums2) { if (cnt[x]-- > 0) { ans.push(x); } } return ans; }
351
Android Unlock Patterns
Medium
<p>Android devices have a special lock screen with a <code>3 x 3</code> grid of dots. Users can set an &quot;unlock pattern&quot; by connecting the dots in a specific sequence, forming a series of joined line segments where each segment&#39;s endpoints are two consecutive dots in the sequence. A sequence of <code>k</code> dots is a <strong>valid</strong> unlock pattern if both of the following are true:</p> <ul> <li>All the dots in the sequence are <strong>distinct</strong>.</li> <li>If the line segment connecting two consecutive dots in the sequence passes through the <strong>center</strong> of any other dot, the other dot <strong>must have previously appeared</strong> in the sequence. No jumps through the center non-selected dots are allowed. <ul> <li>For example, connecting dots <code>2</code> and <code>9</code> without dots <code>5</code> or <code>6</code> appearing beforehand is valid because the line from dot <code>2</code> to dot <code>9</code> does not pass through the center of either dot <code>5</code> or <code>6</code>.</li> <li>However, connecting dots <code>1</code> and <code>3</code> without dot <code>2</code> appearing beforehand is invalid because the line from dot <code>1</code> to dot <code>3</code> passes through the center of dot <code>2</code>.</li> </ul> </li> </ul> <p>Here are some example valid and invalid unlock patterns:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0351.Android%20Unlock%20Patterns/images/android-unlock.png" style="width: 418px; height: 128px;" /></p> <ul> <li>The 1st pattern <code>[4,1,3,6]</code> is invalid because the line connecting dots <code>1</code> and <code>3</code> pass through dot <code>2</code>, but dot <code>2</code> did not previously appear in the sequence.</li> <li>The 2nd pattern <code>[4,1,9,2]</code> is invalid because the line connecting dots <code>1</code> and <code>9</code> pass through dot <code>5</code>, but dot <code>5</code> did not previously appear in the sequence.</li> <li>The 3rd pattern <code>[2,4,1,3,6]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>3</code> meets the condition because dot <code>2</code> previously appeared in the sequence.</li> <li>The 4th pattern <code>[6,5,4,1,9,2]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>9</code> meets the condition because dot <code>5</code> previously appeared in the sequence.</li> </ul> <p>Given two integers <code>m</code> and <code>n</code>, return <em>the <strong>number of unique and valid unlock patterns</strong> of the Android grid lock screen that consist of <strong>at least</strong> </em><code>m</code><em> keys and <strong>at most</strong> </em><code>n</code><em> keys.</em></p> <p>Two unlock patterns are considered <strong>unique</strong> if there is a dot in one sequence that is not in the other, or the order of the dots is different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1 <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 2 <strong>Output:</strong> 65 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 9</code></li> </ul>
Bit Manipulation; Dynamic Programming; Backtracking; Bitmask
C++
class Solution { public: int numberOfPatterns(int m, int n) { int cross[10][10]; memset(cross, 0, sizeof(cross)); bool vis[10]; memset(vis, false, sizeof(vis)); cross[1][3] = cross[3][1] = 2; cross[1][7] = cross[7][1] = 4; cross[1][9] = cross[9][1] = 5; cross[2][8] = cross[8][2] = 5; cross[3][7] = cross[7][3] = 5; cross[3][9] = cross[9][3] = 6; cross[4][6] = cross[6][4] = 5; cross[7][9] = cross[9][7] = 8; function<int(int, int)> dfs = [&](int i, int cnt) { if (cnt > n) { return 0; } vis[i] = true; int ans = cnt >= m ? 1 : 0; for (int j = 1; j < 10; ++j) { int x = cross[i][j]; if (!vis[j] && (x == 0 || vis[x])) { ans += dfs(j, cnt + 1); } } vis[i] = false; return ans; }; return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1); } };
351
Android Unlock Patterns
Medium
<p>Android devices have a special lock screen with a <code>3 x 3</code> grid of dots. Users can set an &quot;unlock pattern&quot; by connecting the dots in a specific sequence, forming a series of joined line segments where each segment&#39;s endpoints are two consecutive dots in the sequence. A sequence of <code>k</code> dots is a <strong>valid</strong> unlock pattern if both of the following are true:</p> <ul> <li>All the dots in the sequence are <strong>distinct</strong>.</li> <li>If the line segment connecting two consecutive dots in the sequence passes through the <strong>center</strong> of any other dot, the other dot <strong>must have previously appeared</strong> in the sequence. No jumps through the center non-selected dots are allowed. <ul> <li>For example, connecting dots <code>2</code> and <code>9</code> without dots <code>5</code> or <code>6</code> appearing beforehand is valid because the line from dot <code>2</code> to dot <code>9</code> does not pass through the center of either dot <code>5</code> or <code>6</code>.</li> <li>However, connecting dots <code>1</code> and <code>3</code> without dot <code>2</code> appearing beforehand is invalid because the line from dot <code>1</code> to dot <code>3</code> passes through the center of dot <code>2</code>.</li> </ul> </li> </ul> <p>Here are some example valid and invalid unlock patterns:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0351.Android%20Unlock%20Patterns/images/android-unlock.png" style="width: 418px; height: 128px;" /></p> <ul> <li>The 1st pattern <code>[4,1,3,6]</code> is invalid because the line connecting dots <code>1</code> and <code>3</code> pass through dot <code>2</code>, but dot <code>2</code> did not previously appear in the sequence.</li> <li>The 2nd pattern <code>[4,1,9,2]</code> is invalid because the line connecting dots <code>1</code> and <code>9</code> pass through dot <code>5</code>, but dot <code>5</code> did not previously appear in the sequence.</li> <li>The 3rd pattern <code>[2,4,1,3,6]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>3</code> meets the condition because dot <code>2</code> previously appeared in the sequence.</li> <li>The 4th pattern <code>[6,5,4,1,9,2]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>9</code> meets the condition because dot <code>5</code> previously appeared in the sequence.</li> </ul> <p>Given two integers <code>m</code> and <code>n</code>, return <em>the <strong>number of unique and valid unlock patterns</strong> of the Android grid lock screen that consist of <strong>at least</strong> </em><code>m</code><em> keys and <strong>at most</strong> </em><code>n</code><em> keys.</em></p> <p>Two unlock patterns are considered <strong>unique</strong> if there is a dot in one sequence that is not in the other, or the order of the dots is different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1 <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 2 <strong>Output:</strong> 65 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 9</code></li> </ul>
Bit Manipulation; Dynamic Programming; Backtracking; Bitmask
Go
func numberOfPatterns(m int, n int) int { cross := [10][10]int{} vis := [10]bool{} cross[1][3] = 2 cross[1][7] = 4 cross[1][9] = 5 cross[2][8] = 5 cross[3][7] = 5 cross[3][9] = 6 cross[4][6] = 5 cross[7][9] = 8 cross[3][1] = 2 cross[7][1] = 4 cross[9][1] = 5 cross[8][2] = 5 cross[7][3] = 5 cross[9][3] = 6 cross[6][4] = 5 cross[9][7] = 8 var dfs func(int, int) int dfs = func(i, cnt int) int { if cnt > n { return 0 } vis[i] = true ans := 0 if cnt >= m { ans++ } for j := 1; j < 10; j++ { x := cross[i][j] if !vis[j] && (x == 0 || vis[x]) { ans += dfs(j, cnt+1) } } vis[i] = false return ans } return dfs(1, 1)*4 + dfs(2, 1)*4 + dfs(5, 1) }
351
Android Unlock Patterns
Medium
<p>Android devices have a special lock screen with a <code>3 x 3</code> grid of dots. Users can set an &quot;unlock pattern&quot; by connecting the dots in a specific sequence, forming a series of joined line segments where each segment&#39;s endpoints are two consecutive dots in the sequence. A sequence of <code>k</code> dots is a <strong>valid</strong> unlock pattern if both of the following are true:</p> <ul> <li>All the dots in the sequence are <strong>distinct</strong>.</li> <li>If the line segment connecting two consecutive dots in the sequence passes through the <strong>center</strong> of any other dot, the other dot <strong>must have previously appeared</strong> in the sequence. No jumps through the center non-selected dots are allowed. <ul> <li>For example, connecting dots <code>2</code> and <code>9</code> without dots <code>5</code> or <code>6</code> appearing beforehand is valid because the line from dot <code>2</code> to dot <code>9</code> does not pass through the center of either dot <code>5</code> or <code>6</code>.</li> <li>However, connecting dots <code>1</code> and <code>3</code> without dot <code>2</code> appearing beforehand is invalid because the line from dot <code>1</code> to dot <code>3</code> passes through the center of dot <code>2</code>.</li> </ul> </li> </ul> <p>Here are some example valid and invalid unlock patterns:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0351.Android%20Unlock%20Patterns/images/android-unlock.png" style="width: 418px; height: 128px;" /></p> <ul> <li>The 1st pattern <code>[4,1,3,6]</code> is invalid because the line connecting dots <code>1</code> and <code>3</code> pass through dot <code>2</code>, but dot <code>2</code> did not previously appear in the sequence.</li> <li>The 2nd pattern <code>[4,1,9,2]</code> is invalid because the line connecting dots <code>1</code> and <code>9</code> pass through dot <code>5</code>, but dot <code>5</code> did not previously appear in the sequence.</li> <li>The 3rd pattern <code>[2,4,1,3,6]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>3</code> meets the condition because dot <code>2</code> previously appeared in the sequence.</li> <li>The 4th pattern <code>[6,5,4,1,9,2]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>9</code> meets the condition because dot <code>5</code> previously appeared in the sequence.</li> </ul> <p>Given two integers <code>m</code> and <code>n</code>, return <em>the <strong>number of unique and valid unlock patterns</strong> of the Android grid lock screen that consist of <strong>at least</strong> </em><code>m</code><em> keys and <strong>at most</strong> </em><code>n</code><em> keys.</em></p> <p>Two unlock patterns are considered <strong>unique</strong> if there is a dot in one sequence that is not in the other, or the order of the dots is different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1 <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 2 <strong>Output:</strong> 65 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 9</code></li> </ul>
Bit Manipulation; Dynamic Programming; Backtracking; Bitmask
Java
class Solution { private int m; private int n; private int[][] cross = new int[10][10]; private boolean[] vis = new boolean[10]; public int numberOfPatterns(int m, int n) { this.m = m; this.n = n; cross[1][3] = cross[3][1] = 2; cross[1][7] = cross[7][1] = 4; cross[1][9] = cross[9][1] = 5; cross[2][8] = cross[8][2] = 5; cross[3][7] = cross[7][3] = 5; cross[3][9] = cross[9][3] = 6; cross[4][6] = cross[6][4] = 5; cross[7][9] = cross[9][7] = 8; return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1); } private int dfs(int i, int cnt) { if (cnt > n) { return 0; } vis[i] = true; int ans = cnt >= m ? 1 : 0; for (int j = 1; j < 10; ++j) { int x = cross[i][j]; if (!vis[j] && (x == 0 || vis[x])) { ans += dfs(j, cnt + 1); } } vis[i] = false; return ans; } }
351
Android Unlock Patterns
Medium
<p>Android devices have a special lock screen with a <code>3 x 3</code> grid of dots. Users can set an &quot;unlock pattern&quot; by connecting the dots in a specific sequence, forming a series of joined line segments where each segment&#39;s endpoints are two consecutive dots in the sequence. A sequence of <code>k</code> dots is a <strong>valid</strong> unlock pattern if both of the following are true:</p> <ul> <li>All the dots in the sequence are <strong>distinct</strong>.</li> <li>If the line segment connecting two consecutive dots in the sequence passes through the <strong>center</strong> of any other dot, the other dot <strong>must have previously appeared</strong> in the sequence. No jumps through the center non-selected dots are allowed. <ul> <li>For example, connecting dots <code>2</code> and <code>9</code> without dots <code>5</code> or <code>6</code> appearing beforehand is valid because the line from dot <code>2</code> to dot <code>9</code> does not pass through the center of either dot <code>5</code> or <code>6</code>.</li> <li>However, connecting dots <code>1</code> and <code>3</code> without dot <code>2</code> appearing beforehand is invalid because the line from dot <code>1</code> to dot <code>3</code> passes through the center of dot <code>2</code>.</li> </ul> </li> </ul> <p>Here are some example valid and invalid unlock patterns:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0351.Android%20Unlock%20Patterns/images/android-unlock.png" style="width: 418px; height: 128px;" /></p> <ul> <li>The 1st pattern <code>[4,1,3,6]</code> is invalid because the line connecting dots <code>1</code> and <code>3</code> pass through dot <code>2</code>, but dot <code>2</code> did not previously appear in the sequence.</li> <li>The 2nd pattern <code>[4,1,9,2]</code> is invalid because the line connecting dots <code>1</code> and <code>9</code> pass through dot <code>5</code>, but dot <code>5</code> did not previously appear in the sequence.</li> <li>The 3rd pattern <code>[2,4,1,3,6]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>3</code> meets the condition because dot <code>2</code> previously appeared in the sequence.</li> <li>The 4th pattern <code>[6,5,4,1,9,2]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>9</code> meets the condition because dot <code>5</code> previously appeared in the sequence.</li> </ul> <p>Given two integers <code>m</code> and <code>n</code>, return <em>the <strong>number of unique and valid unlock patterns</strong> of the Android grid lock screen that consist of <strong>at least</strong> </em><code>m</code><em> keys and <strong>at most</strong> </em><code>n</code><em> keys.</em></p> <p>Two unlock patterns are considered <strong>unique</strong> if there is a dot in one sequence that is not in the other, or the order of the dots is different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1 <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 2 <strong>Output:</strong> 65 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 9</code></li> </ul>
Bit Manipulation; Dynamic Programming; Backtracking; Bitmask
Python
class Solution: def numberOfPatterns(self, m: int, n: int) -> int: def dfs(i: int, cnt: int = 1) -> int: if cnt > n: return 0 vis[i] = True ans = int(cnt >= m) for j in range(1, 10): x = cross[i][j] if not vis[j] and (x == 0 or vis[x]): ans += dfs(j, cnt + 1) vis[i] = False return ans cross = [[0] * 10 for _ in range(10)] cross[1][3] = cross[3][1] = 2 cross[1][7] = cross[7][1] = 4 cross[1][9] = cross[9][1] = 5 cross[2][8] = cross[8][2] = 5 cross[3][7] = cross[7][3] = 5 cross[3][9] = cross[9][3] = 6 cross[4][6] = cross[6][4] = 5 cross[7][9] = cross[9][7] = 8 vis = [False] * 10 return dfs(1) * 4 + dfs(2) * 4 + dfs(5)
351
Android Unlock Patterns
Medium
<p>Android devices have a special lock screen with a <code>3 x 3</code> grid of dots. Users can set an &quot;unlock pattern&quot; by connecting the dots in a specific sequence, forming a series of joined line segments where each segment&#39;s endpoints are two consecutive dots in the sequence. A sequence of <code>k</code> dots is a <strong>valid</strong> unlock pattern if both of the following are true:</p> <ul> <li>All the dots in the sequence are <strong>distinct</strong>.</li> <li>If the line segment connecting two consecutive dots in the sequence passes through the <strong>center</strong> of any other dot, the other dot <strong>must have previously appeared</strong> in the sequence. No jumps through the center non-selected dots are allowed. <ul> <li>For example, connecting dots <code>2</code> and <code>9</code> without dots <code>5</code> or <code>6</code> appearing beforehand is valid because the line from dot <code>2</code> to dot <code>9</code> does not pass through the center of either dot <code>5</code> or <code>6</code>.</li> <li>However, connecting dots <code>1</code> and <code>3</code> without dot <code>2</code> appearing beforehand is invalid because the line from dot <code>1</code> to dot <code>3</code> passes through the center of dot <code>2</code>.</li> </ul> </li> </ul> <p>Here are some example valid and invalid unlock patterns:</p> <p><img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0351.Android%20Unlock%20Patterns/images/android-unlock.png" style="width: 418px; height: 128px;" /></p> <ul> <li>The 1st pattern <code>[4,1,3,6]</code> is invalid because the line connecting dots <code>1</code> and <code>3</code> pass through dot <code>2</code>, but dot <code>2</code> did not previously appear in the sequence.</li> <li>The 2nd pattern <code>[4,1,9,2]</code> is invalid because the line connecting dots <code>1</code> and <code>9</code> pass through dot <code>5</code>, but dot <code>5</code> did not previously appear in the sequence.</li> <li>The 3rd pattern <code>[2,4,1,3,6]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>3</code> meets the condition because dot <code>2</code> previously appeared in the sequence.</li> <li>The 4th pattern <code>[6,5,4,1,9,2]</code> is valid because it follows the conditions. The line connecting dots <code>1</code> and <code>9</code> meets the condition because dot <code>5</code> previously appeared in the sequence.</li> </ul> <p>Given two integers <code>m</code> and <code>n</code>, return <em>the <strong>number of unique and valid unlock patterns</strong> of the Android grid lock screen that consist of <strong>at least</strong> </em><code>m</code><em> keys and <strong>at most</strong> </em><code>n</code><em> keys.</em></p> <p>Two unlock patterns are considered <strong>unique</strong> if there is a dot in one sequence that is not in the other, or the order of the dots is different.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 1 <strong>Output:</strong> 9 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> m = 1, n = 2 <strong>Output:</strong> 65 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= m, n &lt;= 9</code></li> </ul>
Bit Manipulation; Dynamic Programming; Backtracking; Bitmask
TypeScript
function numberOfPatterns(m: number, n: number): number { const cross: number[][] = Array(10) .fill(0) .map(() => Array(10).fill(0)); const vis: boolean[] = Array(10).fill(false); cross[1][3] = cross[3][1] = 2; cross[1][7] = cross[7][1] = 4; cross[1][9] = cross[9][1] = 5; cross[2][8] = cross[8][2] = 5; cross[3][7] = cross[7][3] = 5; cross[3][9] = cross[9][3] = 6; cross[4][6] = cross[6][4] = 5; cross[7][9] = cross[9][7] = 8; const dfs = (i: number, cnt: number): number => { if (cnt > n) { return 0; } vis[i] = true; let ans = 0; if (cnt >= m) { ++ans; } for (let j = 1; j < 10; ++j) { const x = cross[i][j]; if (!vis[j] && (x === 0 || vis[x])) { ans += dfs(j, cnt + 1); } } vis[i] = false; return ans; }; return dfs(1, 1) * 4 + dfs(2, 1) * 4 + dfs(5, 1); }
352
Data Stream as Disjoint Intervals
Hard
<p>Given a data stream input of non-negative integers <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code>, summarize the numbers seen so far as a list of disjoint intervals.</p> <p>Implement the <code>SummaryRanges</code> class:</p> <ul> <li><code>SummaryRanges()</code> Initializes the object with an empty stream.</li> <li><code>void addNum(int value)</code> Adds the integer <code>value</code> to the stream.</li> <li><code>int[][] getIntervals()</code> Returns a summary of the integers in the stream currently as a list of disjoint intervals <code>[start<sub>i</sub>, end<sub>i</sub>]</code>. The answer should be sorted by <code>start<sub>i</sub></code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;SummaryRanges&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;] [[], [1], [], [3], [], [7], [], [2], [], [6], []] <strong>Output</strong> [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] <strong>Explanation</strong> SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = [1] summaryRanges.getIntervals(); // return [[1, 1]] summaryRanges.addNum(3); // arr = [1, 3] summaryRanges.getIntervals(); // return [[1, 1], [3, 3]] summaryRanges.addNum(7); // arr = [1, 3, 7] summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]] summaryRanges.addNum(2); // arr = [1, 2, 3, 7] summaryRanges.getIntervals(); // return [[1, 3], [7, 7]] summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] summaryRanges.getIntervals(); // return [[1, 3], [6, 7]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= value &lt;= 10<sup>4</sup></code></li> <li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>getIntervals</code>.</li> <li>At most <code>10<sup>2</sup></code>&nbsp;calls will be made to&nbsp;<code>getIntervals</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?</p>
Design; Binary Search; Ordered Set
C++
class SummaryRanges { private: map<int, vector<int>> mp; public: SummaryRanges() { } void addNum(int val) { auto r = mp.upper_bound(val); auto l = r == mp.begin() ? mp.end() : prev(r); if (l != mp.end() && r != mp.end() && l->second[1] + 1 == val && r->second[0] - 1 == val) { l->second[1] = r->second[1]; mp.erase(r); } else if (l != mp.end() && val <= l->second[1] + 1) l->second[1] = max(val, l->second[1]); else if (r != mp.end() && val >= r->second[0] - 1) r->second[0] = min(val, r->second[0]); else mp[val] = {val, val}; } vector<vector<int>> getIntervals() { vector<vector<int>> res; for (auto& range : mp) res.push_back(range.second); return res; } }; /** * Your SummaryRanges object will be instantiated and called as such: * SummaryRanges* obj = new SummaryRanges(); * obj->addNum(val); * vector<vector<int>> param_2 = obj->getIntervals(); */
352
Data Stream as Disjoint Intervals
Hard
<p>Given a data stream input of non-negative integers <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code>, summarize the numbers seen so far as a list of disjoint intervals.</p> <p>Implement the <code>SummaryRanges</code> class:</p> <ul> <li><code>SummaryRanges()</code> Initializes the object with an empty stream.</li> <li><code>void addNum(int value)</code> Adds the integer <code>value</code> to the stream.</li> <li><code>int[][] getIntervals()</code> Returns a summary of the integers in the stream currently as a list of disjoint intervals <code>[start<sub>i</sub>, end<sub>i</sub>]</code>. The answer should be sorted by <code>start<sub>i</sub></code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;SummaryRanges&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;] [[], [1], [], [3], [], [7], [], [2], [], [6], []] <strong>Output</strong> [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] <strong>Explanation</strong> SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = [1] summaryRanges.getIntervals(); // return [[1, 1]] summaryRanges.addNum(3); // arr = [1, 3] summaryRanges.getIntervals(); // return [[1, 1], [3, 3]] summaryRanges.addNum(7); // arr = [1, 3, 7] summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]] summaryRanges.addNum(2); // arr = [1, 2, 3, 7] summaryRanges.getIntervals(); // return [[1, 3], [7, 7]] summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] summaryRanges.getIntervals(); // return [[1, 3], [6, 7]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= value &lt;= 10<sup>4</sup></code></li> <li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>getIntervals</code>.</li> <li>At most <code>10<sup>2</sup></code>&nbsp;calls will be made to&nbsp;<code>getIntervals</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?</p>
Design; Binary Search; Ordered Set
Java
class SummaryRanges { private TreeMap<Integer, int[]> mp; public SummaryRanges() { mp = new TreeMap<>(); } public void addNum(int val) { Integer l = mp.floorKey(val); Integer r = mp.ceilingKey(val); if (l != null && r != null && mp.get(l)[1] + 1 == val && mp.get(r)[0] - 1 == val) { mp.get(l)[1] = mp.get(r)[1]; mp.remove(r); } else if (l != null && val <= mp.get(l)[1] + 1) { mp.get(l)[1] = Math.max(val, mp.get(l)[1]); } else if (r != null && val >= mp.get(r)[0] - 1) { mp.get(r)[0] = Math.min(val, mp.get(r)[0]); } else { mp.put(val, new int[] {val, val}); } } public int[][] getIntervals() { int[][] res = new int[mp.size()][2]; int i = 0; for (int[] range : mp.values()) { res[i++] = range; } return res; } } /** * Your SummaryRanges object will be instantiated and called as such: * SummaryRanges obj = new SummaryRanges(); * obj.addNum(val); * int[][] param_2 = obj.getIntervals(); */
352
Data Stream as Disjoint Intervals
Hard
<p>Given a data stream input of non-negative integers <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code>, summarize the numbers seen so far as a list of disjoint intervals.</p> <p>Implement the <code>SummaryRanges</code> class:</p> <ul> <li><code>SummaryRanges()</code> Initializes the object with an empty stream.</li> <li><code>void addNum(int value)</code> Adds the integer <code>value</code> to the stream.</li> <li><code>int[][] getIntervals()</code> Returns a summary of the integers in the stream currently as a list of disjoint intervals <code>[start<sub>i</sub>, end<sub>i</sub>]</code>. The answer should be sorted by <code>start<sub>i</sub></code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;SummaryRanges&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;] [[], [1], [], [3], [], [7], [], [2], [], [6], []] <strong>Output</strong> [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] <strong>Explanation</strong> SummaryRanges summaryRanges = new SummaryRanges(); summaryRanges.addNum(1); // arr = [1] summaryRanges.getIntervals(); // return [[1, 1]] summaryRanges.addNum(3); // arr = [1, 3] summaryRanges.getIntervals(); // return [[1, 1], [3, 3]] summaryRanges.addNum(7); // arr = [1, 3, 7] summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]] summaryRanges.addNum(2); // arr = [1, 2, 3, 7] summaryRanges.getIntervals(); // return [[1, 3], [7, 7]] summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] summaryRanges.getIntervals(); // return [[1, 3], [6, 7]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= value &lt;= 10<sup>4</sup></code></li> <li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>getIntervals</code>.</li> <li>At most <code>10<sup>2</sup></code>&nbsp;calls will be made to&nbsp;<code>getIntervals</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?</p>
Design; Binary Search; Ordered Set
Python
class SummaryRanges: def __init__(self): self.mp = SortedDict() def addNum(self, val: int) -> None: n = len(self.mp) ridx = self.mp.bisect_right(val) lidx = n if ridx == 0 else ridx - 1 keys = self.mp.keys() values = self.mp.values() if ( lidx != n and ridx != n and values[lidx][1] + 1 == val and values[ridx][0] - 1 == val ): self.mp[keys[lidx]][1] = self.mp[keys[ridx]][1] self.mp.pop(keys[ridx]) elif lidx != n and val <= values[lidx][1] + 1: self.mp[keys[lidx]][1] = max(val, self.mp[keys[lidx]][1]) elif ridx != n and val >= values[ridx][0] - 1: self.mp[keys[ridx]][0] = min(val, self.mp[keys[ridx]][0]) else: self.mp[val] = [val, val] def getIntervals(self) -> List[List[int]]: return list(self.mp.values()) # # Your SummaryRanges object will be instantiated and called as such: # # obj = SummaryRanges() # # obj.addNum(val) # # param_2 = obj.getIntervals()
353
Design Snake Game
Medium
<p>Design a <a href="https://en.wikipedia.org/wiki/Snake_(video_game)" target="_blank">Snake game</a> that is played on a device with screen size <code>height x width</code>. <a href="http://patorjk.com/games/snake/" target="_blank">Play the game online</a> if you are not familiar with the game.</p> <p>The snake is initially positioned at the top left corner <code>(0, 0)</code> with a length of <code>1</code> unit.</p> <p>You are given an array <code>food</code> where <code>food[i] = (r<sub>i</sub>, c<sub>i</sub>)</code> is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game&#39;s score both increase by <code>1</code>.</p> <p>Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.</p> <p>When a piece of food appears on the screen, it is <strong>guaranteed</strong> that it will not appear on a block occupied by the snake.</p> <p>The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies <strong>after</strong> moving (i.e. a snake of length 4 cannot run into itself).</p> <p>Implement the <code>SnakeGame</code> class:</p> <ul> <li><code>SnakeGame(int width, int height, int[][] food)</code> Initializes the object with a screen of size <code>height x width</code> and the positions of the <code>food</code>.</li> <li><code>int move(String direction)</code> Returns the score of the game after applying one <code>direction</code> move by the snake. If the game is over, return <code>-1</code>.</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/0353.Design%20Snake%20Game/images/snake.jpg" style="width: 800px; height: 302px;" /> <pre> <strong>Input</strong> [&quot;SnakeGame&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3, 2, [[1, 2], [0, 1]]], [&quot;R&quot;], [&quot;D&quot;], [&quot;R&quot;], [&quot;U&quot;], [&quot;L&quot;], [&quot;U&quot;]] <strong>Output</strong> [null, 0, 0, 1, 1, 2, -1] <strong>Explanation</strong> SnakeGame snakeGame = new SnakeGame(3, 2, [[1, 2], [0, 1]]); snakeGame.move(&quot;R&quot;); // return 0 snakeGame.move(&quot;D&quot;); // return 0 snakeGame.move(&quot;R&quot;); // return 1, snake eats the first piece of food. The second piece of food appears at (0, 1). snakeGame.move(&quot;U&quot;); // return 1 snakeGame.move(&quot;L&quot;); // return 2, snake eats the second food. No more food appears. snakeGame.move(&quot;U&quot;); // return -1, game over because snake collides with border </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= width, height &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= food.length &lt;= 50</code></li> <li><code>food[i].length == 2</code></li> <li><code>0 &lt;= r<sub>i</sub> &lt; height</code></li> <li><code>0 &lt;= c<sub>i</sub> &lt; width</code></li> <li><code>direction.length == 1</code></li> <li><code>direction</code> is <code>&#39;U&#39;</code>, <code>&#39;D&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;R&#39;</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>move</code>.</li> </ul>
Design; Queue; Array; Hash Table; Simulation
C++
class SnakeGame { public: SnakeGame(int width, int height, vector<vector<int>>& food) { m = height; n = width; this->food = food; score = 0; idx = 0; q.push_back(0); vis.insert(0); } int move(string direction) { int p = q.front(); int i = p / n, j = p % n; int x = i, y = j; if (direction == "U") { --x; } else if (direction == "D") { ++x; } else if (direction == "L") { --y; } else { ++y; } if (x < 0 || x >= m || y < 0 || y >= n) { return -1; } if (idx < food.size() && x == food[idx][0] && y == food[idx][1]) { ++score; ++idx; } else { int tail = q.back(); q.pop_back(); vis.erase(tail); } int cur = f(x, y); if (vis.count(cur)) { return -1; } q.push_front(cur); vis.insert(cur); return score; } private: int m; int n; vector<vector<int>> food; int score; int idx; deque<int> q; unordered_set<int> vis; int f(int i, int j) { return i * n + j; } }; /** * Your SnakeGame object will be instantiated and called as such: * SnakeGame* obj = new SnakeGame(width, height, food); * int param_1 = obj->move(direction); */
353
Design Snake Game
Medium
<p>Design a <a href="https://en.wikipedia.org/wiki/Snake_(video_game)" target="_blank">Snake game</a> that is played on a device with screen size <code>height x width</code>. <a href="http://patorjk.com/games/snake/" target="_blank">Play the game online</a> if you are not familiar with the game.</p> <p>The snake is initially positioned at the top left corner <code>(0, 0)</code> with a length of <code>1</code> unit.</p> <p>You are given an array <code>food</code> where <code>food[i] = (r<sub>i</sub>, c<sub>i</sub>)</code> is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game&#39;s score both increase by <code>1</code>.</p> <p>Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.</p> <p>When a piece of food appears on the screen, it is <strong>guaranteed</strong> that it will not appear on a block occupied by the snake.</p> <p>The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies <strong>after</strong> moving (i.e. a snake of length 4 cannot run into itself).</p> <p>Implement the <code>SnakeGame</code> class:</p> <ul> <li><code>SnakeGame(int width, int height, int[][] food)</code> Initializes the object with a screen of size <code>height x width</code> and the positions of the <code>food</code>.</li> <li><code>int move(String direction)</code> Returns the score of the game after applying one <code>direction</code> move by the snake. If the game is over, return <code>-1</code>.</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/0353.Design%20Snake%20Game/images/snake.jpg" style="width: 800px; height: 302px;" /> <pre> <strong>Input</strong> [&quot;SnakeGame&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3, 2, [[1, 2], [0, 1]]], [&quot;R&quot;], [&quot;D&quot;], [&quot;R&quot;], [&quot;U&quot;], [&quot;L&quot;], [&quot;U&quot;]] <strong>Output</strong> [null, 0, 0, 1, 1, 2, -1] <strong>Explanation</strong> SnakeGame snakeGame = new SnakeGame(3, 2, [[1, 2], [0, 1]]); snakeGame.move(&quot;R&quot;); // return 0 snakeGame.move(&quot;D&quot;); // return 0 snakeGame.move(&quot;R&quot;); // return 1, snake eats the first piece of food. The second piece of food appears at (0, 1). snakeGame.move(&quot;U&quot;); // return 1 snakeGame.move(&quot;L&quot;); // return 2, snake eats the second food. No more food appears. snakeGame.move(&quot;U&quot;); // return -1, game over because snake collides with border </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= width, height &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= food.length &lt;= 50</code></li> <li><code>food[i].length == 2</code></li> <li><code>0 &lt;= r<sub>i</sub> &lt; height</code></li> <li><code>0 &lt;= c<sub>i</sub> &lt; width</code></li> <li><code>direction.length == 1</code></li> <li><code>direction</code> is <code>&#39;U&#39;</code>, <code>&#39;D&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;R&#39;</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>move</code>.</li> </ul>
Design; Queue; Array; Hash Table; Simulation
Go
type SnakeGame struct { m int n int food [][]int score int idx int q []int vis map[int]bool } func Constructor(width int, height int, food [][]int) SnakeGame { return SnakeGame{height, width, food, 0, 0, []int{0}, map[int]bool{}} } func (this *SnakeGame) Move(direction string) int { f := func(i, j int) int { return i*this.n + j } p := this.q[0] i, j := p/this.n, p%this.n x, y := i, j if direction == "U" { x-- } else if direction == "D" { x++ } else if direction == "L" { y-- } else { y++ } if x < 0 || x >= this.m || y < 0 || y >= this.n { return -1 } if this.idx < len(this.food) && x == this.food[this.idx][0] && y == this.food[this.idx][1] { this.score++ this.idx++ } else { t := this.q[len(this.q)-1] this.q = this.q[:len(this.q)-1] this.vis[t] = false } cur := f(x, y) if this.vis[cur] { return -1 } this.q = append([]int{cur}, this.q...) this.vis[cur] = true return this.score } /** * Your SnakeGame object will be instantiated and called as such: * obj := Constructor(width, height, food); * param_1 := obj.Move(direction); */
353
Design Snake Game
Medium
<p>Design a <a href="https://en.wikipedia.org/wiki/Snake_(video_game)" target="_blank">Snake game</a> that is played on a device with screen size <code>height x width</code>. <a href="http://patorjk.com/games/snake/" target="_blank">Play the game online</a> if you are not familiar with the game.</p> <p>The snake is initially positioned at the top left corner <code>(0, 0)</code> with a length of <code>1</code> unit.</p> <p>You are given an array <code>food</code> where <code>food[i] = (r<sub>i</sub>, c<sub>i</sub>)</code> is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game&#39;s score both increase by <code>1</code>.</p> <p>Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.</p> <p>When a piece of food appears on the screen, it is <strong>guaranteed</strong> that it will not appear on a block occupied by the snake.</p> <p>The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies <strong>after</strong> moving (i.e. a snake of length 4 cannot run into itself).</p> <p>Implement the <code>SnakeGame</code> class:</p> <ul> <li><code>SnakeGame(int width, int height, int[][] food)</code> Initializes the object with a screen of size <code>height x width</code> and the positions of the <code>food</code>.</li> <li><code>int move(String direction)</code> Returns the score of the game after applying one <code>direction</code> move by the snake. If the game is over, return <code>-1</code>.</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/0353.Design%20Snake%20Game/images/snake.jpg" style="width: 800px; height: 302px;" /> <pre> <strong>Input</strong> [&quot;SnakeGame&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3, 2, [[1, 2], [0, 1]]], [&quot;R&quot;], [&quot;D&quot;], [&quot;R&quot;], [&quot;U&quot;], [&quot;L&quot;], [&quot;U&quot;]] <strong>Output</strong> [null, 0, 0, 1, 1, 2, -1] <strong>Explanation</strong> SnakeGame snakeGame = new SnakeGame(3, 2, [[1, 2], [0, 1]]); snakeGame.move(&quot;R&quot;); // return 0 snakeGame.move(&quot;D&quot;); // return 0 snakeGame.move(&quot;R&quot;); // return 1, snake eats the first piece of food. The second piece of food appears at (0, 1). snakeGame.move(&quot;U&quot;); // return 1 snakeGame.move(&quot;L&quot;); // return 2, snake eats the second food. No more food appears. snakeGame.move(&quot;U&quot;); // return -1, game over because snake collides with border </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= width, height &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= food.length &lt;= 50</code></li> <li><code>food[i].length == 2</code></li> <li><code>0 &lt;= r<sub>i</sub> &lt; height</code></li> <li><code>0 &lt;= c<sub>i</sub> &lt; width</code></li> <li><code>direction.length == 1</code></li> <li><code>direction</code> is <code>&#39;U&#39;</code>, <code>&#39;D&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;R&#39;</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>move</code>.</li> </ul>
Design; Queue; Array; Hash Table; Simulation
Java
class SnakeGame { private int m; private int n; private int[][] food; private int score; private int idx; private Deque<Integer> q = new ArrayDeque<>(); private Set<Integer> vis = new HashSet<>(); public SnakeGame(int width, int height, int[][] food) { m = height; n = width; this.food = food; q.offer(0); vis.add(0); } public int move(String direction) { int p = q.peekFirst(); int i = p / n, j = p % n; int x = i, y = j; if ("U".equals(direction)) { --x; } else if ("D".equals(direction)) { ++x; } else if ("L".equals(direction)) { --y; } else { ++y; } if (x < 0 || x >= m || y < 0 || y >= n) { return -1; } if (idx < food.length && x == food[idx][0] && y == food[idx][1]) { ++score; ++idx; } else { int t = q.pollLast(); vis.remove(t); } int cur = f(x, y); if (vis.contains(cur)) { return -1; } q.offerFirst(cur); vis.add(cur); return score; } private int f(int i, int j) { return i * n + j; } } /** * Your SnakeGame object will be instantiated and called as such: * SnakeGame obj = new SnakeGame(width, height, food); * int param_1 = obj.move(direction); */
353
Design Snake Game
Medium
<p>Design a <a href="https://en.wikipedia.org/wiki/Snake_(video_game)" target="_blank">Snake game</a> that is played on a device with screen size <code>height x width</code>. <a href="http://patorjk.com/games/snake/" target="_blank">Play the game online</a> if you are not familiar with the game.</p> <p>The snake is initially positioned at the top left corner <code>(0, 0)</code> with a length of <code>1</code> unit.</p> <p>You are given an array <code>food</code> where <code>food[i] = (r<sub>i</sub>, c<sub>i</sub>)</code> is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game&#39;s score both increase by <code>1</code>.</p> <p>Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.</p> <p>When a piece of food appears on the screen, it is <strong>guaranteed</strong> that it will not appear on a block occupied by the snake.</p> <p>The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies <strong>after</strong> moving (i.e. a snake of length 4 cannot run into itself).</p> <p>Implement the <code>SnakeGame</code> class:</p> <ul> <li><code>SnakeGame(int width, int height, int[][] food)</code> Initializes the object with a screen of size <code>height x width</code> and the positions of the <code>food</code>.</li> <li><code>int move(String direction)</code> Returns the score of the game after applying one <code>direction</code> move by the snake. If the game is over, return <code>-1</code>.</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/0353.Design%20Snake%20Game/images/snake.jpg" style="width: 800px; height: 302px;" /> <pre> <strong>Input</strong> [&quot;SnakeGame&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3, 2, [[1, 2], [0, 1]]], [&quot;R&quot;], [&quot;D&quot;], [&quot;R&quot;], [&quot;U&quot;], [&quot;L&quot;], [&quot;U&quot;]] <strong>Output</strong> [null, 0, 0, 1, 1, 2, -1] <strong>Explanation</strong> SnakeGame snakeGame = new SnakeGame(3, 2, [[1, 2], [0, 1]]); snakeGame.move(&quot;R&quot;); // return 0 snakeGame.move(&quot;D&quot;); // return 0 snakeGame.move(&quot;R&quot;); // return 1, snake eats the first piece of food. The second piece of food appears at (0, 1). snakeGame.move(&quot;U&quot;); // return 1 snakeGame.move(&quot;L&quot;); // return 2, snake eats the second food. No more food appears. snakeGame.move(&quot;U&quot;); // return -1, game over because snake collides with border </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= width, height &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= food.length &lt;= 50</code></li> <li><code>food[i].length == 2</code></li> <li><code>0 &lt;= r<sub>i</sub> &lt; height</code></li> <li><code>0 &lt;= c<sub>i</sub> &lt; width</code></li> <li><code>direction.length == 1</code></li> <li><code>direction</code> is <code>&#39;U&#39;</code>, <code>&#39;D&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;R&#39;</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>move</code>.</li> </ul>
Design; Queue; Array; Hash Table; Simulation
Python
class SnakeGame: def __init__(self, width: int, height: int, food: List[List[int]]): self.m = height self.n = width self.food = food self.score = 0 self.idx = 0 self.q = deque([(0, 0)]) self.vis = {(0, 0)} def move(self, direction: str) -> int: i, j = self.q[0] x, y = i, j match direction: case "U": x -= 1 case "D": x += 1 case "L": y -= 1 case "R": y += 1 if x < 0 or x >= self.m or y < 0 or y >= self.n: return -1 if ( self.idx < len(self.food) and x == self.food[self.idx][0] and y == self.food[self.idx][1] ): self.score += 1 self.idx += 1 else: self.vis.remove(self.q.pop()) if (x, y) in self.vis: return -1 self.q.appendleft((x, y)) self.vis.add((x, y)) return self.score # Your SnakeGame object will be instantiated and called as such: # obj = SnakeGame(width, height, food) # param_1 = obj.move(direction)
353
Design Snake Game
Medium
<p>Design a <a href="https://en.wikipedia.org/wiki/Snake_(video_game)" target="_blank">Snake game</a> that is played on a device with screen size <code>height x width</code>. <a href="http://patorjk.com/games/snake/" target="_blank">Play the game online</a> if you are not familiar with the game.</p> <p>The snake is initially positioned at the top left corner <code>(0, 0)</code> with a length of <code>1</code> unit.</p> <p>You are given an array <code>food</code> where <code>food[i] = (r<sub>i</sub>, c<sub>i</sub>)</code> is the row and column position of a piece of food that the snake can eat. When a snake eats a piece of food, its length and the game&#39;s score both increase by <code>1</code>.</p> <p>Each piece of food appears one by one on the screen, meaning the second piece of food will not appear until the snake eats the first piece of food.</p> <p>When a piece of food appears on the screen, it is <strong>guaranteed</strong> that it will not appear on a block occupied by the snake.</p> <p>The game is over if the snake goes out of bounds (hits a wall) or if its head occupies a space that its body occupies <strong>after</strong> moving (i.e. a snake of length 4 cannot run into itself).</p> <p>Implement the <code>SnakeGame</code> class:</p> <ul> <li><code>SnakeGame(int width, int height, int[][] food)</code> Initializes the object with a screen of size <code>height x width</code> and the positions of the <code>food</code>.</li> <li><code>int move(String direction)</code> Returns the score of the game after applying one <code>direction</code> move by the snake. If the game is over, return <code>-1</code>.</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/0353.Design%20Snake%20Game/images/snake.jpg" style="width: 800px; height: 302px;" /> <pre> <strong>Input</strong> [&quot;SnakeGame&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;, &quot;move&quot;] [[3, 2, [[1, 2], [0, 1]]], [&quot;R&quot;], [&quot;D&quot;], [&quot;R&quot;], [&quot;U&quot;], [&quot;L&quot;], [&quot;U&quot;]] <strong>Output</strong> [null, 0, 0, 1, 1, 2, -1] <strong>Explanation</strong> SnakeGame snakeGame = new SnakeGame(3, 2, [[1, 2], [0, 1]]); snakeGame.move(&quot;R&quot;); // return 0 snakeGame.move(&quot;D&quot;); // return 0 snakeGame.move(&quot;R&quot;); // return 1, snake eats the first piece of food. The second piece of food appears at (0, 1). snakeGame.move(&quot;U&quot;); // return 1 snakeGame.move(&quot;L&quot;); // return 2, snake eats the second food. No more food appears. snakeGame.move(&quot;U&quot;); // return -1, game over because snake collides with border </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= width, height &lt;= 10<sup>4</sup></code></li> <li><code>1 &lt;= food.length &lt;= 50</code></li> <li><code>food[i].length == 2</code></li> <li><code>0 &lt;= r<sub>i</sub> &lt; height</code></li> <li><code>0 &lt;= c<sub>i</sub> &lt; width</code></li> <li><code>direction.length == 1</code></li> <li><code>direction</code> is <code>&#39;U&#39;</code>, <code>&#39;D&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;R&#39;</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>move</code>.</li> </ul>
Design; Queue; Array; Hash Table; Simulation
TypeScript
class SnakeGame { private m: number; private n: number; private food: number[][]; private score: number; private idx: number; private q: number[]; private vis: Set<number>; constructor(width: number, height: number, food: number[][]) { this.m = height; this.n = width; this.food = food; this.score = 0; this.idx = 0; this.q = [0]; this.vis = new Set([0]); } move(direction: string): number { const p = this.q[0]; const i = Math.floor(p / this.n); const j = p % this.n; let x = i; let y = j; if (direction === 'U') { --x; } else if (direction === 'D') { ++x; } else if (direction === 'L') { --y; } else { ++y; } if (x < 0 || x >= this.m || y < 0 || y >= this.n) { return -1; } if ( this.idx < this.food.length && x === this.food[this.idx][0] && y === this.food[this.idx][1] ) { ++this.score; ++this.idx; } else { const t = this.q.pop()!; this.vis.delete(t); } const cur = x * this.n + y; if (this.vis.has(cur)) { return -1; } this.q.unshift(cur); this.vis.add(cur); return this.score; } } /** * Your SnakeGame object will be instantiated and called as such: * var obj = new SnakeGame(width, height, food) * var param_1 = obj.move(direction) */
354
Russian Doll Envelopes
Hard
<p>You are given a 2D array of integers <code>envelopes</code> where <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> represents the width and the height of an envelope.</p> <p>One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope&#39;s width and height.</p> <p>Return <em>the maximum number of envelopes you can Russian doll (i.e., put one inside the other)</em>.</p> <p><strong>Note:</strong> You cannot rotate an envelope.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The maximum number of envelopes you can Russian doll is <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> envelopes = [[1,1],[1,1],[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li> <li><code>envelopes[i].length == 2</code></li> <li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Dynamic Programming; Sorting
C++
class Solution { public: int maxEnvelopes(vector<vector<int>>& envelopes) { sort(envelopes.begin(), envelopes.end(), [](const auto& e1, const auto& e2) { return e1[0] < e2[0] || (e1[0] == e2[0] && e1[1] > e2[1]); }); int n = envelopes.size(); vector<int> d{envelopes[0][1]}; for (int i = 1; i < n; ++i) { int x = envelopes[i][1]; if (x > d[d.size() - 1]) d.push_back(x); else { int idx = lower_bound(d.begin(), d.end(), x) - d.begin(); if (idx == d.size()) idx = 0; d[idx] = x; } } return d.size(); } };
354
Russian Doll Envelopes
Hard
<p>You are given a 2D array of integers <code>envelopes</code> where <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> represents the width and the height of an envelope.</p> <p>One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope&#39;s width and height.</p> <p>Return <em>the maximum number of envelopes you can Russian doll (i.e., put one inside the other)</em>.</p> <p><strong>Note:</strong> You cannot rotate an envelope.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The maximum number of envelopes you can Russian doll is <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> envelopes = [[1,1],[1,1],[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li> <li><code>envelopes[i].length == 2</code></li> <li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Dynamic Programming; Sorting
Go
func maxEnvelopes(envelopes [][]int) int { sort.Slice(envelopes, func(i, j int) bool { if envelopes[i][0] != envelopes[j][0] { return envelopes[i][0] < envelopes[j][0] } return envelopes[j][1] < envelopes[i][1] }) n := len(envelopes) d := make([]int, n+1) d[1] = envelopes[0][1] size := 1 for _, e := range envelopes[1:] { x := e[1] if x > d[size] { size++ d[size] = x } else { left, right := 1, size for left < right { mid := (left + right) >> 1 if d[mid] >= x { right = mid } else { left = mid + 1 } } if d[left] < x { left = 1 } d[left] = x } } return size }
354
Russian Doll Envelopes
Hard
<p>You are given a 2D array of integers <code>envelopes</code> where <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> represents the width and the height of an envelope.</p> <p>One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope&#39;s width and height.</p> <p>Return <em>the maximum number of envelopes you can Russian doll (i.e., put one inside the other)</em>.</p> <p><strong>Note:</strong> You cannot rotate an envelope.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The maximum number of envelopes you can Russian doll is <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> envelopes = [[1,1],[1,1],[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li> <li><code>envelopes[i].length == 2</code></li> <li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Dynamic Programming; Sorting
Java
class Solution { public int maxEnvelopes(int[][] envelopes) { Arrays.sort(envelopes, (a, b) -> { return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]; }); int n = envelopes.length; int[] d = new int[n + 1]; d[1] = envelopes[0][1]; int size = 1; for (int i = 1; i < n; ++i) { int x = envelopes[i][1]; if (x > d[size]) { d[++size] = x; } else { int left = 1, right = size; while (left < right) { int mid = (left + right) >> 1; if (d[mid] >= x) { right = mid; } else { left = mid + 1; } } int p = d[left] >= x ? left : 1; d[p] = x; } } return size; } }
354
Russian Doll Envelopes
Hard
<p>You are given a 2D array of integers <code>envelopes</code> where <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> represents the width and the height of an envelope.</p> <p>One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope&#39;s width and height.</p> <p>Return <em>the maximum number of envelopes you can Russian doll (i.e., put one inside the other)</em>.</p> <p><strong>Note:</strong> You cannot rotate an envelope.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]] <strong>Output:</strong> 3 <strong>Explanation:</strong> The maximum number of envelopes you can Russian doll is <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> envelopes = [[1,1],[1,1],[1,1]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li> <li><code>envelopes[i].length == 2</code></li> <li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Array; Binary Search; Dynamic Programming; Sorting
Python
class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: envelopes.sort(key=lambda x: (x[0], -x[1])) d = [envelopes[0][1]] for _, h in envelopes[1:]: if h > d[-1]: d.append(h) else: idx = bisect_left(d, h) d[idx] = h return len(d)
355
Design Twitter
Medium
<p>Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the <code>10</code> most recent tweets in the user&#39;s news feed.</p> <p>Implement the <code>Twitter</code> class:</p> <ul> <li><code>Twitter()</code> Initializes your twitter object.</li> <li><code>void postTweet(int userId, int tweetId)</code> Composes a new tweet with ID <code>tweetId</code> by the user <code>userId</code>. Each call to this function will be made with a unique <code>tweetId</code>.</li> <li><code>List&lt;Integer&gt; getNewsFeed(int userId)</code> Retrieves the <code>10</code> most recent tweet IDs in the user&#39;s news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be <strong>ordered from most recent to least recent</strong>.</li> <li><code>void follow(int followerId, int followeeId)</code> The user with ID <code>followerId</code> started following the user with ID <code>followeeId</code>.</li> <li><code>void unfollow(int followerId, int followeeId)</code> The user with ID <code>followerId</code> started unfollowing the user with ID <code>followeeId</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Twitter&quot;, &quot;postTweet&quot;, &quot;getNewsFeed&quot;, &quot;follow&quot;, &quot;postTweet&quot;, &quot;getNewsFeed&quot;, &quot;unfollow&quot;, &quot;getNewsFeed&quot;] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] <strong>Output</strong> [null, null, [5], null, null, [6, 5], null, [5]] <strong>Explanation</strong> Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1&#39;s news feed should return a list with 1 tweet id -&gt; [5]. return [5] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // User 1&#39;s news feed should return a list with 2 tweet ids -&gt; [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1&#39;s news feed should return a list with 1 tweet id -&gt; [5], since user 1 is no longer following user 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= userId, followerId, followeeId &lt;= 500</code></li> <li><code>0 &lt;= tweetId &lt;= 10<sup>4</sup></code></li> <li>All the tweets have <strong>unique</strong> IDs.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>postTweet</code>, <code>getNewsFeed</code>, <code>follow</code>, and <code>unfollow</code>.</li> <li>A user cannot follow himself.</li> </ul>
Design; Hash Table; Linked List; Heap (Priority Queue)
Java
class Twitter { private Map<Integer, List<Integer>> userTweets; private Map<Integer, Set<Integer>> userFollowing; private Map<Integer, Integer> tweets; private int time; /** Initialize your data structure here. */ public Twitter() { userTweets = new HashMap<>(); userFollowing = new HashMap<>(); tweets = new HashMap<>(); time = 0; } /** Compose a new tweet. */ public void postTweet(int userId, int tweetId) { userTweets.computeIfAbsent(userId, k -> new ArrayList<>()).add(tweetId); tweets.put(tweetId, ++time); } /** * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed * must be posted by users who the user followed or by the user herself. Tweets must be ordered * from most recent to least recent. */ public List<Integer> getNewsFeed(int userId) { Set<Integer> following = userFollowing.getOrDefault(userId, new HashSet<>()); Set<Integer> users = new HashSet<>(following); users.add(userId); PriorityQueue<Integer> pq = new PriorityQueue<>(10, (a, b) -> (tweets.get(b) - tweets.get(a))); for (Integer u : users) { List<Integer> userTweet = userTweets.get(u); if (userTweet != null && !userTweet.isEmpty()) { for (int i = userTweet.size() - 1, k = 10; i >= 0 && k > 0; --i, --k) { pq.offer(userTweet.get(i)); } } } List<Integer> res = new ArrayList<>(); while (!pq.isEmpty() && res.size() < 10) { res.add(pq.poll()); } return res; } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ public void follow(int followerId, int followeeId) { userFollowing.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId); } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ public void unfollow(int followerId, int followeeId) { userFollowing.computeIfAbsent(followerId, k -> new HashSet<>()).remove(followeeId); } } /** * Your Twitter object will be instantiated and called as such: * Twitter obj = new Twitter(); * obj.postTweet(userId,tweetId); * List<Integer> param_2 = obj.getNewsFeed(userId); * obj.follow(followerId,followeeId); * obj.unfollow(followerId,followeeId); */
355
Design Twitter
Medium
<p>Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the <code>10</code> most recent tweets in the user&#39;s news feed.</p> <p>Implement the <code>Twitter</code> class:</p> <ul> <li><code>Twitter()</code> Initializes your twitter object.</li> <li><code>void postTweet(int userId, int tweetId)</code> Composes a new tweet with ID <code>tweetId</code> by the user <code>userId</code>. Each call to this function will be made with a unique <code>tweetId</code>.</li> <li><code>List&lt;Integer&gt; getNewsFeed(int userId)</code> Retrieves the <code>10</code> most recent tweet IDs in the user&#39;s news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be <strong>ordered from most recent to least recent</strong>.</li> <li><code>void follow(int followerId, int followeeId)</code> The user with ID <code>followerId</code> started following the user with ID <code>followeeId</code>.</li> <li><code>void unfollow(int followerId, int followeeId)</code> The user with ID <code>followerId</code> started unfollowing the user with ID <code>followeeId</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Twitter&quot;, &quot;postTweet&quot;, &quot;getNewsFeed&quot;, &quot;follow&quot;, &quot;postTweet&quot;, &quot;getNewsFeed&quot;, &quot;unfollow&quot;, &quot;getNewsFeed&quot;] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] <strong>Output</strong> [null, null, [5], null, null, [6, 5], null, [5]] <strong>Explanation</strong> Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1&#39;s news feed should return a list with 1 tweet id -&gt; [5]. return [5] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // User 1&#39;s news feed should return a list with 2 tweet ids -&gt; [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1&#39;s news feed should return a list with 1 tweet id -&gt; [5], since user 1 is no longer following user 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= userId, followerId, followeeId &lt;= 500</code></li> <li><code>0 &lt;= tweetId &lt;= 10<sup>4</sup></code></li> <li>All the tweets have <strong>unique</strong> IDs.</li> <li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>postTweet</code>, <code>getNewsFeed</code>, <code>follow</code>, and <code>unfollow</code>.</li> <li>A user cannot follow himself.</li> </ul>
Design; Hash Table; Linked List; Heap (Priority Queue)
Python
class Twitter: def __init__(self): """ Initialize your data structure here. """ self.user_tweets = defaultdict(list) self.user_following = defaultdict(set) self.tweets = defaultdict() self.time = 0 def postTweet(self, userId: int, tweetId: int) -> None: """ Compose a new tweet. """ self.time += 1 self.user_tweets[userId].append(tweetId) self.tweets[tweetId] = self.time def getNewsFeed(self, userId: int) -> List[int]: """ Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. """ following = self.user_following[userId] users = set(following) users.add(userId) tweets = [self.user_tweets[u][::-1][:10] for u in users] tweets = sum(tweets, []) return nlargest(10, tweets, key=lambda tweet: self.tweets[tweet]) def follow(self, followerId: int, followeeId: int) -> None: """ Follower follows a followee. If the operation is invalid, it should be a no-op. """ self.user_following[followerId].add(followeeId) def unfollow(self, followerId: int, followeeId: int) -> None: """ Follower unfollows a followee. If the operation is invalid, it should be a no-op. """ following = self.user_following[followerId] if followeeId in following: following.remove(followeeId) # Your Twitter object will be instantiated and called as such: # obj = Twitter() # obj.postTweet(userId,tweetId) # param_2 = obj.getNewsFeed(userId) # obj.follow(followerId,followeeId) # obj.unfollow(followerId,followeeId)
356
Line Reflection
Medium
<p>Given <code>n</code> points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically.</p> <p>In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points&#39; set is the same as the reflected ones.</p> <p><strong>Note</strong> that there can be repeated points.</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/0356.Line%20Reflection/images/356_example_1.png" style="width: 389px; height: 340px;" /> <pre> <strong>Input:</strong> points = [[1,1],[-1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can choose the line x = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0356.Line%20Reflection/images/356_example_2.png" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> points = [[1,1],[-1,-1]] <strong>Output:</strong> false <strong>Explanation:</strong> We can&#39;t choose a line. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>8</sup> &lt;= points[i][j] &lt;= 10<sup>8</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code>?</p>
Array; Hash Table; Math
C++
class Solution { public: bool isReflected(vector<vector<int>>& points) { const int inf = 1 << 30; int minX = inf, maxX = -inf; set<pair<int, int>> pointSet; for (auto& p : points) { minX = min(minX, p[0]); maxX = max(maxX, p[0]); pointSet.insert({p[0], p[1]}); } int s = minX + maxX; for (auto& p : points) { if (!pointSet.count({s - p[0], p[1]})) { return false; } } return true; } };
356
Line Reflection
Medium
<p>Given <code>n</code> points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically.</p> <p>In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points&#39; set is the same as the reflected ones.</p> <p><strong>Note</strong> that there can be repeated points.</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/0356.Line%20Reflection/images/356_example_1.png" style="width: 389px; height: 340px;" /> <pre> <strong>Input:</strong> points = [[1,1],[-1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can choose the line x = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0356.Line%20Reflection/images/356_example_2.png" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> points = [[1,1],[-1,-1]] <strong>Output:</strong> false <strong>Explanation:</strong> We can&#39;t choose a line. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>8</sup> &lt;= points[i][j] &lt;= 10<sup>8</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code>?</p>
Array; Hash Table; Math
Go
func isReflected(points [][]int) bool { const inf = 1 << 30 minX, maxX := inf, -inf pointSet := map[[2]int]bool{} for _, p := range points { minX = min(minX, p[0]) maxX = max(maxX, p[0]) pointSet[[2]int{p[0], p[1]}] = true } s := minX + maxX for _, p := range points { if !pointSet[[2]int{s - p[0], p[1]}] { return false } } return true }
356
Line Reflection
Medium
<p>Given <code>n</code> points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically.</p> <p>In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points&#39; set is the same as the reflected ones.</p> <p><strong>Note</strong> that there can be repeated points.</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/0356.Line%20Reflection/images/356_example_1.png" style="width: 389px; height: 340px;" /> <pre> <strong>Input:</strong> points = [[1,1],[-1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can choose the line x = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0356.Line%20Reflection/images/356_example_2.png" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> points = [[1,1],[-1,-1]] <strong>Output:</strong> false <strong>Explanation:</strong> We can&#39;t choose a line. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>8</sup> &lt;= points[i][j] &lt;= 10<sup>8</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code>?</p>
Array; Hash Table; Math
Java
class Solution { public boolean isReflected(int[][] points) { final int inf = 1 << 30; int minX = inf, maxX = -inf; Set<List<Integer>> pointSet = new HashSet<>(); for (int[] p : points) { minX = Math.min(minX, p[0]); maxX = Math.max(maxX, p[0]); pointSet.add(List.of(p[0], p[1])); } int s = minX + maxX; for (int[] p : points) { if (!pointSet.contains(List.of(s - p[0], p[1]))) { return false; } } return true; } }
356
Line Reflection
Medium
<p>Given <code>n</code> points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically.</p> <p>In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points&#39; set is the same as the reflected ones.</p> <p><strong>Note</strong> that there can be repeated points.</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/0356.Line%20Reflection/images/356_example_1.png" style="width: 389px; height: 340px;" /> <pre> <strong>Input:</strong> points = [[1,1],[-1,1]] <strong>Output:</strong> true <strong>Explanation:</strong> We can choose the line x = 0. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0356.Line%20Reflection/images/356_example_2.png" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> points = [[1,1],[-1,-1]] <strong>Output:</strong> false <strong>Explanation:</strong> We can&#39;t choose a line. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == points.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li> <li><code>-10<sup>8</sup> &lt;= points[i][j] &lt;= 10<sup>8</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do better than <code>O(n<sup>2</sup>)</code>?</p>
Array; Hash Table; Math
Python
class Solution: def isReflected(self, points: List[List[int]]) -> bool: min_x, max_x = inf, -inf point_set = set() for x, y in points: min_x = min(min_x, x) max_x = max(max_x, x) point_set.add((x, y)) s = min_x + max_x return all((s - x, y) in point_set for x, y in points)
357
Count Numbers with Unique Digits
Medium
<p>Given an integer <code>n</code>, return the count of all numbers with unique digits, <code>x</code>, where <code>0 &lt;= x &lt; 10<sup>n</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 91 <strong>Explanation:</strong> The answer should be the total numbers in the range of 0 &le; x &lt; 100, excluding 11,22,33,44,55,66,77,88,99 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 8</code></li> </ul>
Math; Dynamic Programming; Backtracking
C++
class Solution { public: int countNumbersWithUniqueDigits(int n) { int f[n + 1][1 << 10]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int i, int mask, bool lead) -> int { if (i < 0) { return 1; } if (!lead && f[i][mask] != -1) { return f[i][mask]; } int ans = 0; for (int j = 0; j <= 9; ++j) { if (mask >> j & 1) { continue; } if (lead && j == 0) { ans += dfs(i - 1, mask, true); } else { ans += dfs(i - 1, mask | 1 << i, false); } } if (!lead) { f[i][mask] = ans; } return ans; }; return dfs(n - 1, 0, true); } };
357
Count Numbers with Unique Digits
Medium
<p>Given an integer <code>n</code>, return the count of all numbers with unique digits, <code>x</code>, where <code>0 &lt;= x &lt; 10<sup>n</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 91 <strong>Explanation:</strong> The answer should be the total numbers in the range of 0 &le; x &lt; 100, excluding 11,22,33,44,55,66,77,88,99 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 8</code></li> </ul>
Math; Dynamic Programming; Backtracking
Go
func countNumbersWithUniqueDigits(n int) int { f := make([][1 << 10]int, n) for i := range f { for j := range f[i] { f[i][j] = -1 } } var dfs func(i, mask int, lead bool) int dfs = func(i, mask int, lead bool) int { if i < 0 { return 1 } if !lead && f[i][mask] != -1 { return f[i][mask] } ans := 0 for j := 0; j < 10; j++ { if mask>>j&1 == 1 { continue } if lead && j == 0 { ans += dfs(i-1, mask, true) } else { ans += dfs(i-1, mask|1<<j, false) } } if !lead { f[i][mask] = ans } return ans } return dfs(n-1, 0, true) }
357
Count Numbers with Unique Digits
Medium
<p>Given an integer <code>n</code>, return the count of all numbers with unique digits, <code>x</code>, where <code>0 &lt;= x &lt; 10<sup>n</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 91 <strong>Explanation:</strong> The answer should be the total numbers in the range of 0 &le; x &lt; 100, excluding 11,22,33,44,55,66,77,88,99 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 8</code></li> </ul>
Math; Dynamic Programming; Backtracking
Java
class Solution { private Integer[][] f; public int countNumbersWithUniqueDigits(int n) { f = new Integer[n][1 << 10]; return dfs(n - 1, 0, true); } private int dfs(int i, int mask, boolean lead) { if (i < 0) { return 1; } if (!lead && f[i][mask] != null) { return f[i][mask]; } int ans = 0; for (int j = 0; j <= 9; ++j) { if ((mask >> j & 1) == 1) { continue; } if (lead && j == 0) { ans += dfs(i - 1, mask, true); } else { ans += dfs(i - 1, mask | 1 << j, false); } } if (!lead) { f[i][mask] = ans; } return ans; } }
357
Count Numbers with Unique Digits
Medium
<p>Given an integer <code>n</code>, return the count of all numbers with unique digits, <code>x</code>, where <code>0 &lt;= x &lt; 10<sup>n</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 91 <strong>Explanation:</strong> The answer should be the total numbers in the range of 0 &le; x &lt; 100, excluding 11,22,33,44,55,66,77,88,99 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 8</code></li> </ul>
Math; Dynamic Programming; Backtracking
Python
class Solution: def countNumbersWithUniqueDigits(self, n: int) -> int: @cache def dfs(i: int, mask: int, lead: bool) -> int: if i < 0: return 1 ans = 0 for j in range(10): if mask >> j & 1: continue if lead and j == 0: ans += dfs(i - 1, mask, True) else: ans += dfs(i - 1, mask | 1 << j, False) return ans return dfs(n - 1, 0, True)
357
Count Numbers with Unique Digits
Medium
<p>Given an integer <code>n</code>, return the count of all numbers with unique digits, <code>x</code>, where <code>0 &lt;= x &lt; 10<sup>n</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 2 <strong>Output:</strong> 91 <strong>Explanation:</strong> The answer should be the total numbers in the range of 0 &le; x &lt; 100, excluding 11,22,33,44,55,66,77,88,99 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 8</code></li> </ul>
Math; Dynamic Programming; Backtracking
TypeScript
function countNumbersWithUniqueDigits(n: number): number { const f: number[][] = Array.from({ length: n }, () => Array(1 << 10).fill(-1)); const dfs = (i: number, mask: number, lead: boolean): number => { if (i < 0) { return 1; } if (!lead && f[i][mask] !== -1) { return f[i][mask]; } let ans = 0; for (let j = 0; j < 10; ++j) { if ((mask >> j) & 1) { continue; } if (lead && j === 0) { ans += dfs(i - 1, mask, true); } else { ans += dfs(i - 1, mask | (1 << j), false); } } if (!lead) { f[i][mask] = ans; } return ans; }; return dfs(n - 1, 0, true); }
358
Rearrange String k Distance Apart
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, rearrange <code>s</code> such that the same characters are <strong>at least</strong> distance <code>k</code> from each other. If it is not possible to rearrange the string, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabbcc&quot;, k = 3 <strong>Output:</strong> &quot;abcabc&quot; <strong>Explanation:</strong> The same letters are at least a distance of 3 from each other. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabc&quot;, k = 3 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It is not possible to rearrange the string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaadbbcc&quot;, k = 2 <strong>Output:</strong> &quot;abacabcd&quot; <strong>Explanation:</strong> The same letters are at least a distance of 2 from each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
C++
class Solution { public: string rearrangeString(string s, int k) { vector<int> cnt(26, 0); for (char c : s) { ++cnt[c - 'a']; } priority_queue<pair<int, int>> pq; for (int i = 0; i < 26; ++i) { if (cnt[i] > 0) { pq.emplace(cnt[i], i); } } queue<pair<int, int>> q; string ans; while (!pq.empty()) { auto p = pq.top(); pq.pop(); p.first -= 1; ans.push_back('a' + p.second); q.push(p); if (q.size() >= k) { p = q.front(); q.pop(); if (p.first > 0) { pq.push(p); } } } return ans.size() < s.size() ? "" : ans; } };
358
Rearrange String k Distance Apart
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, rearrange <code>s</code> such that the same characters are <strong>at least</strong> distance <code>k</code> from each other. If it is not possible to rearrange the string, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabbcc&quot;, k = 3 <strong>Output:</strong> &quot;abcabc&quot; <strong>Explanation:</strong> The same letters are at least a distance of 3 from each other. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabc&quot;, k = 3 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It is not possible to rearrange the string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaadbbcc&quot;, k = 2 <strong>Output:</strong> &quot;abacabcd&quot; <strong>Explanation:</strong> The same letters are at least a distance of 2 from each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
Go
func rearrangeString(s string, k int) string { cnt := [26]int{} for _, c := range s { cnt[c-'a']++ } pq := priorityqueue.NewWith(func(a, b any) int { x := a.([2]int) y := b.([2]int) return y[0] - x[0] }) for i := 0; i < 26; i++ { if cnt[i] > 0 { pq.Enqueue([2]int{cnt[i], i}) } } var q [][2]int var ans strings.Builder for pq.Size() > 0 { p, _ := pq.Dequeue() pair := p.([2]int) pair[0]-- ans.WriteByte(byte('a' + pair[1])) q = append(q, pair) if len(q) >= k { front := q[0] q = q[1:] if front[0] > 0 { pq.Enqueue(front) } } } if ans.Len() < len(s) { return "" } return ans.String() }
358
Rearrange String k Distance Apart
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, rearrange <code>s</code> such that the same characters are <strong>at least</strong> distance <code>k</code> from each other. If it is not possible to rearrange the string, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabbcc&quot;, k = 3 <strong>Output:</strong> &quot;abcabc&quot; <strong>Explanation:</strong> The same letters are at least a distance of 3 from each other. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabc&quot;, k = 3 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It is not possible to rearrange the string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaadbbcc&quot;, k = 2 <strong>Output:</strong> &quot;abacabcd&quot; <strong>Explanation:</strong> The same letters are at least a distance of 2 from each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
Java
class Solution { public String rearrangeString(String s, int k) { int[] cnt = new int[26]; for (char c : s.toCharArray()) { ++cnt[c - 'a']; } PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); for (int i = 0; i < cnt.length; ++i) { if (cnt[i] > 0) { pq.offer(new int[] {cnt[i], i}); } } Deque<int[]> q = new ArrayDeque<>(); StringBuilder ans = new StringBuilder(); while (!pq.isEmpty()) { var p = pq.poll(); p[0] -= 1; ans.append((char) ('a' + p[1])); q.offerLast(p); if (q.size() >= k) { p = q.pollFirst(); if (p[0] > 0) { pq.offer(p); } } } return ans.length() < s.length() ? "" : ans.toString(); } }
358
Rearrange String k Distance Apart
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, rearrange <code>s</code> such that the same characters are <strong>at least</strong> distance <code>k</code> from each other. If it is not possible to rearrange the string, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabbcc&quot;, k = 3 <strong>Output:</strong> &quot;abcabc&quot; <strong>Explanation:</strong> The same letters are at least a distance of 3 from each other. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabc&quot;, k = 3 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It is not possible to rearrange the string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaadbbcc&quot;, k = 2 <strong>Output:</strong> &quot;abacabcd&quot; <strong>Explanation:</strong> The same letters are at least a distance of 2 from each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
Python
class Solution: def rearrangeString(self, s: str, k: int) -> str: cnt = Counter(s) pq = [(-v, c) for c, v in cnt.items()] heapify(pq) q = deque() ans = [] while pq: v, c = heappop(pq) ans.append(c) q.append((v + 1, c)) if len(q) >= k: e = q.popleft() if e[0]: heappush(pq, e) return "" if len(ans) < len(s) else "".join(ans)
358
Rearrange String k Distance Apart
Hard
<p>Given a string <code>s</code> and an integer <code>k</code>, rearrange <code>s</code> such that the same characters are <strong>at least</strong> distance <code>k</code> from each other. If it is not possible to rearrange the string, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aabbcc&quot;, k = 3 <strong>Output:</strong> &quot;abcabc&quot; <strong>Explanation:</strong> The same letters are at least a distance of 3 from each other. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabc&quot;, k = 3 <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> It is not possible to rearrange the string. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaadbbcc&quot;, k = 2 <strong>Output:</strong> &quot;abacabcd&quot; <strong>Explanation:</strong> The same letters are at least a distance of 2 from each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>0 &lt;= k &lt;= s.length</code></li> </ul>
Greedy; Hash Table; String; Counting; Sorting; Heap (Priority Queue)
TypeScript
export function rearrangeString(s: string, k: number): string { const cnt: number[] = Array(26).fill(0); for (const c of s) { cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]++; } const pq = new PriorityQueue<[number, number]>((a, b) => b[0] - a[0]); for (let i = 0; i < 26; i++) { if (cnt[i] > 0) { pq.enqueue([cnt[i], i]); } } const q: [number, number][] = []; const ans: string[] = []; while (!pq.isEmpty()) { const [count, idx] = pq.dequeue()!; const newCount = count - 1; ans.push(String.fromCharCode('a'.charCodeAt(0) + idx)); q.push([newCount, idx]); if (q.length >= k) { const [frontCount, frontIdx] = q.shift()!; if (frontCount > 0) { pq.enqueue([frontCount, frontIdx]); } } } return ans.length < s.length ? '' : ans.join(''); }
359
Logger Rate Limiter
Easy
<p>Design a logger system that receives a stream of messages along with their timestamps. Each <strong>unique</strong> message should only be printed <strong>at most every 10 seconds</strong> (i.e. a message printed at timestamp <code>t</code> will prevent other identical messages from being printed until timestamp <code>t + 10</code>).</p> <p>All messages will come in chronological order. Several messages may arrive at the same timestamp.</p> <p>Implement the <code>Logger</code> class:</p> <ul> <li><code>Logger()</code> Initializes the <code>logger</code> object.</li> <li><code>bool shouldPrintMessage(int timestamp, string message)</code> Returns <code>true</code> if the <code>message</code> should be printed in the given <code>timestamp</code>, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Logger&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;] [[], [1, &quot;foo&quot;], [2, &quot;bar&quot;], [3, &quot;foo&quot;], [8, &quot;bar&quot;], [10, &quot;foo&quot;], [11, &quot;foo&quot;]] <strong>Output</strong> [null, true, true, false, false, false, true] <strong>Explanation</strong> Logger logger = new Logger(); logger.shouldPrintMessage(1, &quot;foo&quot;); // return true, next allowed timestamp for &quot;foo&quot; is 1 + 10 = 11 logger.shouldPrintMessage(2, &quot;bar&quot;); // return true, next allowed timestamp for &quot;bar&quot; is 2 + 10 = 12 logger.shouldPrintMessage(3, &quot;foo&quot;); // 3 &lt; 11, return false logger.shouldPrintMessage(8, &quot;bar&quot;); // 8 &lt; 12, return false logger.shouldPrintMessage(10, &quot;foo&quot;); // 10 &lt; 11, return false logger.shouldPrintMessage(11, &quot;foo&quot;); // 11 &gt;= 11, return true, next allowed timestamp for &quot;foo&quot; is 11 + 10 = 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>Every <code>timestamp</code> will be passed in non-decreasing order (chronological order).</li> <li><code>1 &lt;= message.length &lt;= 30</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>shouldPrintMessage</code>.</li> </ul>
Design; Hash Table; Data Stream
C++
class Logger { public: Logger() { } bool shouldPrintMessage(int timestamp, string message) { if (ts.contains(message) && ts[message] > timestamp) { return false; } ts[message] = timestamp + 10; return true; } private: unordered_map<string, int> ts; }; /** * Your Logger object will be instantiated and called as such: * Logger* obj = new Logger(); * bool param_1 = obj->shouldPrintMessage(timestamp,message); */
359
Logger Rate Limiter
Easy
<p>Design a logger system that receives a stream of messages along with their timestamps. Each <strong>unique</strong> message should only be printed <strong>at most every 10 seconds</strong> (i.e. a message printed at timestamp <code>t</code> will prevent other identical messages from being printed until timestamp <code>t + 10</code>).</p> <p>All messages will come in chronological order. Several messages may arrive at the same timestamp.</p> <p>Implement the <code>Logger</code> class:</p> <ul> <li><code>Logger()</code> Initializes the <code>logger</code> object.</li> <li><code>bool shouldPrintMessage(int timestamp, string message)</code> Returns <code>true</code> if the <code>message</code> should be printed in the given <code>timestamp</code>, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Logger&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;] [[], [1, &quot;foo&quot;], [2, &quot;bar&quot;], [3, &quot;foo&quot;], [8, &quot;bar&quot;], [10, &quot;foo&quot;], [11, &quot;foo&quot;]] <strong>Output</strong> [null, true, true, false, false, false, true] <strong>Explanation</strong> Logger logger = new Logger(); logger.shouldPrintMessage(1, &quot;foo&quot;); // return true, next allowed timestamp for &quot;foo&quot; is 1 + 10 = 11 logger.shouldPrintMessage(2, &quot;bar&quot;); // return true, next allowed timestamp for &quot;bar&quot; is 2 + 10 = 12 logger.shouldPrintMessage(3, &quot;foo&quot;); // 3 &lt; 11, return false logger.shouldPrintMessage(8, &quot;bar&quot;); // 8 &lt; 12, return false logger.shouldPrintMessage(10, &quot;foo&quot;); // 10 &lt; 11, return false logger.shouldPrintMessage(11, &quot;foo&quot;); // 11 &gt;= 11, return true, next allowed timestamp for &quot;foo&quot; is 11 + 10 = 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>Every <code>timestamp</code> will be passed in non-decreasing order (chronological order).</li> <li><code>1 &lt;= message.length &lt;= 30</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>shouldPrintMessage</code>.</li> </ul>
Design; Hash Table; Data Stream
Go
type Logger struct { ts map[string]int } func Constructor() Logger { return Logger{ts: make(map[string]int)} } func (this *Logger) ShouldPrintMessage(timestamp int, message string) bool { if t, ok := this.ts[message]; ok && timestamp < t { return false } this.ts[message] = timestamp + 10 return true } /** * Your Logger object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.ShouldPrintMessage(timestamp,message); */
359
Logger Rate Limiter
Easy
<p>Design a logger system that receives a stream of messages along with their timestamps. Each <strong>unique</strong> message should only be printed <strong>at most every 10 seconds</strong> (i.e. a message printed at timestamp <code>t</code> will prevent other identical messages from being printed until timestamp <code>t + 10</code>).</p> <p>All messages will come in chronological order. Several messages may arrive at the same timestamp.</p> <p>Implement the <code>Logger</code> class:</p> <ul> <li><code>Logger()</code> Initializes the <code>logger</code> object.</li> <li><code>bool shouldPrintMessage(int timestamp, string message)</code> Returns <code>true</code> if the <code>message</code> should be printed in the given <code>timestamp</code>, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Logger&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;] [[], [1, &quot;foo&quot;], [2, &quot;bar&quot;], [3, &quot;foo&quot;], [8, &quot;bar&quot;], [10, &quot;foo&quot;], [11, &quot;foo&quot;]] <strong>Output</strong> [null, true, true, false, false, false, true] <strong>Explanation</strong> Logger logger = new Logger(); logger.shouldPrintMessage(1, &quot;foo&quot;); // return true, next allowed timestamp for &quot;foo&quot; is 1 + 10 = 11 logger.shouldPrintMessage(2, &quot;bar&quot;); // return true, next allowed timestamp for &quot;bar&quot; is 2 + 10 = 12 logger.shouldPrintMessage(3, &quot;foo&quot;); // 3 &lt; 11, return false logger.shouldPrintMessage(8, &quot;bar&quot;); // 8 &lt; 12, return false logger.shouldPrintMessage(10, &quot;foo&quot;); // 10 &lt; 11, return false logger.shouldPrintMessage(11, &quot;foo&quot;); // 11 &gt;= 11, return true, next allowed timestamp for &quot;foo&quot; is 11 + 10 = 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>Every <code>timestamp</code> will be passed in non-decreasing order (chronological order).</li> <li><code>1 &lt;= message.length &lt;= 30</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>shouldPrintMessage</code>.</li> </ul>
Design; Hash Table; Data Stream
Java
class Logger { private Map<String, Integer> ts = new HashMap<>(); public Logger() { } public boolean shouldPrintMessage(int timestamp, String message) { int t = ts.getOrDefault(message, 0); if (timestamp < t) { return false; } ts.put(message, timestamp + 10); return true; } } /** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * boolean param_1 = obj.shouldPrintMessage(timestamp,message); */
359
Logger Rate Limiter
Easy
<p>Design a logger system that receives a stream of messages along with their timestamps. Each <strong>unique</strong> message should only be printed <strong>at most every 10 seconds</strong> (i.e. a message printed at timestamp <code>t</code> will prevent other identical messages from being printed until timestamp <code>t + 10</code>).</p> <p>All messages will come in chronological order. Several messages may arrive at the same timestamp.</p> <p>Implement the <code>Logger</code> class:</p> <ul> <li><code>Logger()</code> Initializes the <code>logger</code> object.</li> <li><code>bool shouldPrintMessage(int timestamp, string message)</code> Returns <code>true</code> if the <code>message</code> should be printed in the given <code>timestamp</code>, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Logger&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;] [[], [1, &quot;foo&quot;], [2, &quot;bar&quot;], [3, &quot;foo&quot;], [8, &quot;bar&quot;], [10, &quot;foo&quot;], [11, &quot;foo&quot;]] <strong>Output</strong> [null, true, true, false, false, false, true] <strong>Explanation</strong> Logger logger = new Logger(); logger.shouldPrintMessage(1, &quot;foo&quot;); // return true, next allowed timestamp for &quot;foo&quot; is 1 + 10 = 11 logger.shouldPrintMessage(2, &quot;bar&quot;); // return true, next allowed timestamp for &quot;bar&quot; is 2 + 10 = 12 logger.shouldPrintMessage(3, &quot;foo&quot;); // 3 &lt; 11, return false logger.shouldPrintMessage(8, &quot;bar&quot;); // 8 &lt; 12, return false logger.shouldPrintMessage(10, &quot;foo&quot;); // 10 &lt; 11, return false logger.shouldPrintMessage(11, &quot;foo&quot;); // 11 &gt;= 11, return true, next allowed timestamp for &quot;foo&quot; is 11 + 10 = 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>Every <code>timestamp</code> will be passed in non-decreasing order (chronological order).</li> <li><code>1 &lt;= message.length &lt;= 30</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>shouldPrintMessage</code>.</li> </ul>
Design; Hash Table; Data Stream
JavaScript
/** * Initialize your data structure here. */ var Logger = function () { this.limiter = {}; }; /** * Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. * @param {number} timestamp * @param {string} message * @return {boolean} */ Logger.prototype.shouldPrintMessage = function (timestamp, message) { const t = this.limiter[message] || 0; if (t > timestamp) { return false; } this.limiter[message] = timestamp + 10; return true; }; /** * Your Logger object will be instantiated and called as such: * var obj = new Logger() * var param_1 = obj.shouldPrintMessage(timestamp,message) */
359
Logger Rate Limiter
Easy
<p>Design a logger system that receives a stream of messages along with their timestamps. Each <strong>unique</strong> message should only be printed <strong>at most every 10 seconds</strong> (i.e. a message printed at timestamp <code>t</code> will prevent other identical messages from being printed until timestamp <code>t + 10</code>).</p> <p>All messages will come in chronological order. Several messages may arrive at the same timestamp.</p> <p>Implement the <code>Logger</code> class:</p> <ul> <li><code>Logger()</code> Initializes the <code>logger</code> object.</li> <li><code>bool shouldPrintMessage(int timestamp, string message)</code> Returns <code>true</code> if the <code>message</code> should be printed in the given <code>timestamp</code>, otherwise returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Logger&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;, &quot;shouldPrintMessage&quot;] [[], [1, &quot;foo&quot;], [2, &quot;bar&quot;], [3, &quot;foo&quot;], [8, &quot;bar&quot;], [10, &quot;foo&quot;], [11, &quot;foo&quot;]] <strong>Output</strong> [null, true, true, false, false, false, true] <strong>Explanation</strong> Logger logger = new Logger(); logger.shouldPrintMessage(1, &quot;foo&quot;); // return true, next allowed timestamp for &quot;foo&quot; is 1 + 10 = 11 logger.shouldPrintMessage(2, &quot;bar&quot;); // return true, next allowed timestamp for &quot;bar&quot; is 2 + 10 = 12 logger.shouldPrintMessage(3, &quot;foo&quot;); // 3 &lt; 11, return false logger.shouldPrintMessage(8, &quot;bar&quot;); // 8 &lt; 12, return false logger.shouldPrintMessage(10, &quot;foo&quot;); // 10 &lt; 11, return false logger.shouldPrintMessage(11, &quot;foo&quot;); // 11 &gt;= 11, return true, next allowed timestamp for &quot;foo&quot; is 11 + 10 = 21 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li> <li>Every <code>timestamp</code> will be passed in non-decreasing order (chronological order).</li> <li><code>1 &lt;= message.length &lt;= 30</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>shouldPrintMessage</code>.</li> </ul>
Design; Hash Table; Data Stream
Python
class Logger: def __init__(self): self.ts = {} def shouldPrintMessage(self, timestamp: int, message: str) -> bool: t = self.ts.get(message, 0) if t > timestamp: return False self.ts[message] = timestamp + 10 return True # Your Logger object will be instantiated and called as such: # obj = Logger() # param_1 = obj.shouldPrintMessage(timestamp,message)
360
Sort Transformed Array
Medium
<p>Given a <strong>sorted</strong> integer array <code>nums</code> and three integers <code>a</code>, <code>b</code> and <code>c</code>, apply a quadratic function of the form <code>f(x) = ax<sup>2</sup> + bx + c</code> to each element <code>nums[i]</code> in the array, and return <em>the array in a sorted order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = 1, b = 3, c = 5 <strong>Output:</strong> [3,9,15,33] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = -1, b = 3, c = 5 <strong>Output:</strong> [-23,-5,1,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-100 &lt;= nums[i], a, b, c &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>ascending</strong> order.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time?</p>
Array; Math; Two Pointers; Sorting
C++
class Solution { public: vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) { int n = nums.size(); vector<int> ans(n); int i = 0, j = n - 1; auto f = [&](int x) { return a * x * x + b * x + c; }; for (int k = 0; k < n; k++) { int y1 = f(nums[i]); int y2 = f(nums[j]); if (a > 0) { if (y1 > y2) { ans[n - k - 1] = y1; i++; } else { ans[n - k - 1] = y2; j--; } } else { if (y1 > y2) { ans[k] = y2; j--; } else { ans[k] = y1; i++; } } } return ans; } };
360
Sort Transformed Array
Medium
<p>Given a <strong>sorted</strong> integer array <code>nums</code> and three integers <code>a</code>, <code>b</code> and <code>c</code>, apply a quadratic function of the form <code>f(x) = ax<sup>2</sup> + bx + c</code> to each element <code>nums[i]</code> in the array, and return <em>the array in a sorted order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = 1, b = 3, c = 5 <strong>Output:</strong> [3,9,15,33] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = -1, b = 3, c = 5 <strong>Output:</strong> [-23,-5,1,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-100 &lt;= nums[i], a, b, c &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>ascending</strong> order.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time?</p>
Array; Math; Two Pointers; Sorting
Go
func sortTransformedArray(nums []int, a int, b int, c int) []int { f := func(x int) int { return a*x*x + b*x + c } n := len(nums) ans := make([]int, n) i, j := 0, n-1 for k := 0; k < n; k++ { y1, y2 := f(nums[i]), f(nums[j]) if a > 0 { if y1 > y2 { ans[n-k-1] = y1 i++ } else { ans[n-k-1] = y2 j-- } } else { if y1 > y2 { ans[k] = y2 j-- } else { ans[k] = y1 i++ } } } return ans }
360
Sort Transformed Array
Medium
<p>Given a <strong>sorted</strong> integer array <code>nums</code> and three integers <code>a</code>, <code>b</code> and <code>c</code>, apply a quadratic function of the form <code>f(x) = ax<sup>2</sup> + bx + c</code> to each element <code>nums[i]</code> in the array, and return <em>the array in a sorted order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = 1, b = 3, c = 5 <strong>Output:</strong> [3,9,15,33] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = -1, b = 3, c = 5 <strong>Output:</strong> [-23,-5,1,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-100 &lt;= nums[i], a, b, c &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>ascending</strong> order.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time?</p>
Array; Math; Two Pointers; Sorting
Java
class Solution { public int[] sortTransformedArray(int[] nums, int a, int b, int c) { int n = nums.length; int[] ans = new int[n]; int i = 0, j = n - 1; IntUnaryOperator f = x -> a * x * x + b * x + c; for (int k = 0; k < n; k++) { int y1 = f.applyAsInt(nums[i]); int y2 = f.applyAsInt(nums[j]); if (a > 0) { if (y1 > y2) { ans[n - k - 1] = y1; i++; } else { ans[n - k - 1] = y2; j--; } } else { if (y1 > y2) { ans[k] = y2; j--; } else { ans[k] = y1; i++; } } } return ans; } }
360
Sort Transformed Array
Medium
<p>Given a <strong>sorted</strong> integer array <code>nums</code> and three integers <code>a</code>, <code>b</code> and <code>c</code>, apply a quadratic function of the form <code>f(x) = ax<sup>2</sup> + bx + c</code> to each element <code>nums[i]</code> in the array, and return <em>the array in a sorted order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = 1, b = 3, c = 5 <strong>Output:</strong> [3,9,15,33] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = -1, b = 3, c = 5 <strong>Output:</strong> [-23,-5,1,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-100 &lt;= nums[i], a, b, c &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>ascending</strong> order.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time?</p>
Array; Math; Two Pointers; Sorting
JavaScript
/** * @param {number[]} nums * @param {number} a * @param {number} b * @param {number} c * @return {number[]} */ var sortTransformedArray = function (nums, a, b, c) { const f = x => a * x * x + b * x + c; const n = nums.length; let [i, j] = [0, n - 1]; const ans = Array(n); for (let k = 0; k < n; ++k) { const y1 = f(nums[i]); const y2 = f(nums[j]); if (a > 0) { if (y1 > y2) { ans[n - k - 1] = y1; ++i; } else { ans[n - k - 1] = y2; --j; } } else { if (y1 > y2) { ans[k] = y2; --j; } else { ans[k] = y1; ++i; } } } return ans; };
360
Sort Transformed Array
Medium
<p>Given a <strong>sorted</strong> integer array <code>nums</code> and three integers <code>a</code>, <code>b</code> and <code>c</code>, apply a quadratic function of the form <code>f(x) = ax<sup>2</sup> + bx + c</code> to each element <code>nums[i]</code> in the array, and return <em>the array in a sorted order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = 1, b = 3, c = 5 <strong>Output:</strong> [3,9,15,33] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = -1, b = 3, c = 5 <strong>Output:</strong> [-23,-5,1,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-100 &lt;= nums[i], a, b, c &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>ascending</strong> order.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time?</p>
Array; Math; Two Pointers; Sorting
Python
class Solution: def sortTransformedArray( self, nums: List[int], a: int, b: int, c: int ) -> List[int]: def f(x: int) -> int: return a * x * x + b * x + c n = len(nums) i, j = 0, n - 1 ans = [0] * n for k in range(n): y1, y2 = f(nums[i]), f(nums[j]) if a > 0: if y1 > y2: ans[n - k - 1] = y1 i += 1 else: ans[n - k - 1] = y2 j -= 1 else: if y1 > y2: ans[k] = y2 j -= 1 else: ans[k] = y1 i += 1 return ans
360
Sort Transformed Array
Medium
<p>Given a <strong>sorted</strong> integer array <code>nums</code> and three integers <code>a</code>, <code>b</code> and <code>c</code>, apply a quadratic function of the form <code>f(x) = ax<sup>2</sup> + bx + c</code> to each element <code>nums[i]</code> in the array, and return <em>the array in a sorted order</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = 1, b = 3, c = 5 <strong>Output:</strong> [3,9,15,33] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [-4,-2,2,4], a = -1, b = 3, c = 5 <strong>Output:</strong> [-23,-5,1,7] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-100 &lt;= nums[i], a, b, c &lt;= 100</code></li> <li><code>nums</code> is sorted in <strong>ascending</strong> order.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time?</p>
Array; Math; Two Pointers; Sorting
TypeScript
function sortTransformedArray(nums: number[], a: number, b: number, c: number): number[] { const f = (x: number): number => a * x * x + b * x + c; const n = nums.length; let [i, j] = [0, n - 1]; const ans: number[] = Array(n); for (let k = 0; k < n; ++k) { const y1 = f(nums[i]); const y2 = f(nums[j]); if (a > 0) { if (y1 > y2) { ans[n - k - 1] = y1; ++i; } else { ans[n - k - 1] = y2; --j; } } else { if (y1 > y2) { ans[k] = y2; --j; } else { ans[k] = y1; ++i; } } } return ans; }