id
int64
1
3.64k
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
157
Read N Characters Given Read4
Easy
<p>Given a <code>file</code> and assume that you can only read the file using a given method <code>read4</code>, implement a method to read <code>n</code> characters.</p> <p><strong>Method read4: </strong></p> <p>The API <code>read4</code> reads <strong>four consecutive characters</strong> from <code>file</code>, then writes those characters into the buffer array <code>buf4</code>.</p> <p>The return value is the number of actual characters read.</p> <p>Note that <code>read4()</code> has its own file pointer, much like <code>FILE *fp</code> in C.</p> <p><strong>Definition of read4:</strong></p> <pre> Parameter: char[] buf4 Returns: int buf4[] is a destination, not a source. The results from read4 will be copied to buf4[]. </pre> <p>Below is a high-level example of how <code>read4</code> works:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0157.Read%20N%20Characters%20Given%20Read4/images/157_example.png" style="width: 600px; height: 403px;" /> <pre> File file(&quot;abcde<code>&quot;); // File is &quot;</code>abcde<code>&quot;, initially file pointer (fp) points to &#39;a&#39; char[] buf4 = new char[4]; // Create buffer with enough space to store characters read4(buf4); // read4 returns 4. Now buf4 = &quot;abcd&quot;, fp points to &#39;e&#39; read4(buf4); // read4 returns 1. Now buf4 = &quot;e&quot;, fp points to end of file read4(buf4); // read4 returns 0. Now buf4 = &quot;&quot;, fp points to end of file</code> </pre> <p>&nbsp;</p> <p><strong>Method read:</strong></p> <p>By using the <code>read4</code> method, implement the method read that reads <code>n</code> characters from <code>file</code> and store it in the buffer array <code>buf</code>. Consider that you cannot manipulate <code>file</code> directly.</p> <p>The return value is the number of actual characters read.</p> <p><strong>Definition of read: </strong></p> <pre> Parameters: char[] buf, int n Returns: int buf[] is a destination, not a source. You will need to write the results to buf[]. </pre> <p><strong>Note:</strong></p> <ul> <li>Consider that you cannot manipulate the file directly. The file is only accessible for <code>read4</code> but not for <code>read</code>.</li> <li>The <code>read</code> function will only be called once for each test case.</li> <li>You may assume the destination buffer array, <code>buf</code>, is guaranteed to have enough space for storing <code>n</code> characters.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, n = 4 <strong>Output:</strong> 3 <strong>Explanation:</strong> After calling your read method, buf should contain &quot;abc&quot;. We read a total of 3 characters from the file, so return 3. Note that &quot;abc&quot; is the file&#39;s content, not buf. buf is the destination buffer that you will have to write the results to. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> file = &quot;abcde&quot;, n = 5 <strong>Output:</strong> 5 <strong>Explanation:</strong> After calling your read method, buf should contain &quot;abcde&quot;. We read a total of 5 characters from the file, so return 5. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> file = &quot;abcdABCD1234&quot;, n = 12 <strong>Output:</strong> 12 <strong>Explanation:</strong> After calling your read method, buf should contain &quot;abcdABCD1234&quot;. We read a total of 12 characters from the file, so return 12. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= file.length &lt;= 500</code></li> <li><code>file</code> consist of English letters and digits.</li> <li><code>1 &lt;= n &lt;= 1000</code></li> </ul>
Array; Interactive; Simulation
Python
""" The read4 API is already defined for you. @param buf4, a list of characters @return an integer def read4(buf4): # Below is an example of how the read4 API can be called. file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a' buf4 = [' '] * 4 # Create buffer with enough space to store characters read4(buf4) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e' read4(buf4) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i' read4(buf4) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file """ class Solution: def read(self, buf, n): """ :type buf: Destination buffer (List[str]) :type n: Number of characters to read (int) :rtype: The number of actual characters read (int) """ i = 0 buf4 = [0] * 4 v = 5 while v >= 4: v = read4(buf4) for j in range(v): buf[i] = buf4[j] i += 1 if i >= n: return n return i
158
Read N Characters Given read4 II - Call Multiple Times
Hard
<p>Given a <code>file</code> and assume that you can only read the file using a given method <code>read4</code>, implement a method <code>read</code> to read <code>n</code> characters. Your method <code>read</code> may be <strong>called multiple times</strong>.</p> <p><strong>Method read4: </strong></p> <p>The API <code>read4</code> reads <strong>four consecutive characters</strong> from <code>file</code>, then writes those characters into the buffer array <code>buf4</code>.</p> <p>The return value is the number of actual characters read.</p> <p>Note that <code>read4()</code> has its own file pointer, much like <code>FILE *fp</code> in C.</p> <p><strong>Definition of read4:</strong></p> <pre> Parameter: char[] buf4 Returns: int buf4[] is a destination, not a source. The results from read4 will be copied to buf4[]. </pre> <p>Below is a high-level example of how <code>read4</code> works:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0158.Read%20N%20Characters%20Given%20read4%20II%20-%20Call%20Multiple%20Times/images/157_example.png" style="width: 600px; height: 403px;" /> <pre> File file(&quot;abcde<code>&quot;); // File is &quot;</code>abcde<code>&quot;, initially file pointer (fp) points to &#39;a&#39; char[] buf4 = new char[4]; // Create buffer with enough space to store characters read4(buf4); // read4 returns 4. Now buf4 = &quot;abcd&quot;, fp points to &#39;e&#39; read4(buf4); // read4 returns 1. Now buf4 = &quot;e&quot;, fp points to end of file read4(buf4); // read4 returns 0. Now buf4 = &quot;&quot;, fp points to end of file</code> </pre> <p>&nbsp;</p> <p><strong>Method read:</strong></p> <p>By using the <code>read4</code> method, implement the method read that reads <code>n</code> characters from <code>file</code> and store it in the buffer array <code>buf</code>. Consider that you cannot manipulate <code>file</code> directly.</p> <p>The return value is the number of actual characters read.</p> <p><strong>Definition of read: </strong></p> <pre> Parameters: char[] buf, int n Returns: int buf[] is a destination, not a source. You will need to write the results to buf[]. </pre> <p><strong>Note:</strong></p> <ul> <li>Consider that you cannot manipulate the file directly. The file is only accessible for <code>read4</code> but not for <code>read</code>.</li> <li>The read function may be <strong>called multiple times</strong>.</li> <li>Please remember to <strong>RESET</strong> your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see <a href="https://leetcode.com/faq/" target="_blank">here</a> for more details.</li> <li>You may assume the destination buffer array, <code>buf</code>, is guaranteed to have enough space for storing <code>n</code> characters.</li> <li>It is guaranteed that in a given test case the same buffer <code>buf</code> is called by <code>read</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, queries = [1,2,1] <strong>Output:</strong> [1,2,0] <strong>Explanation:</strong> The test case represents the following scenario: File file(&quot;abc&quot;); Solution sol; sol.read(buf, 1); // After calling your read method, buf should contain &quot;a&quot;. We read a total of 1 character from the file, so return 1. sol.read(buf, 2); // Now buf should contain &quot;bc&quot;. We read a total of 2 characters from the file, so return 2. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. Assume buf is allocated and guaranteed to have enough space for storing all characters from the file. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, queries = [4,1] <strong>Output:</strong> [3,0] <strong>Explanation:</strong> The test case represents the following scenario: File file(&quot;abc&quot;); Solution sol; sol.read(buf, 4); // After calling your read method, buf should contain &quot;abc&quot;. We read a total of 3 characters from the file, so return 3. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= file.length &lt;= 500</code></li> <li><code>file</code> consist of English letters and digits.</li> <li><code>1 &lt;= queries.length &lt;= 10</code></li> <li><code>1 &lt;= queries[i] &lt;= 500</code></li> </ul>
Array; Interactive; Simulation
C++
/** * The read4 API is defined in the parent class Reader4. * int read4(char *buf4); */ class Solution { public: /** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */ int read(char* buf, int n) { int j = 0; while (j < n) { if (i == size) { size = read4(buf4); i = 0; if (size == 0) break; } while (j < n && i < size) buf[j++] = buf4[i++]; } return j; } private: char* buf4 = new char[4]; int i = 0; int size = 0; };
158
Read N Characters Given read4 II - Call Multiple Times
Hard
<p>Given a <code>file</code> and assume that you can only read the file using a given method <code>read4</code>, implement a method <code>read</code> to read <code>n</code> characters. Your method <code>read</code> may be <strong>called multiple times</strong>.</p> <p><strong>Method read4: </strong></p> <p>The API <code>read4</code> reads <strong>four consecutive characters</strong> from <code>file</code>, then writes those characters into the buffer array <code>buf4</code>.</p> <p>The return value is the number of actual characters read.</p> <p>Note that <code>read4()</code> has its own file pointer, much like <code>FILE *fp</code> in C.</p> <p><strong>Definition of read4:</strong></p> <pre> Parameter: char[] buf4 Returns: int buf4[] is a destination, not a source. The results from read4 will be copied to buf4[]. </pre> <p>Below is a high-level example of how <code>read4</code> works:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0158.Read%20N%20Characters%20Given%20read4%20II%20-%20Call%20Multiple%20Times/images/157_example.png" style="width: 600px; height: 403px;" /> <pre> File file(&quot;abcde<code>&quot;); // File is &quot;</code>abcde<code>&quot;, initially file pointer (fp) points to &#39;a&#39; char[] buf4 = new char[4]; // Create buffer with enough space to store characters read4(buf4); // read4 returns 4. Now buf4 = &quot;abcd&quot;, fp points to &#39;e&#39; read4(buf4); // read4 returns 1. Now buf4 = &quot;e&quot;, fp points to end of file read4(buf4); // read4 returns 0. Now buf4 = &quot;&quot;, fp points to end of file</code> </pre> <p>&nbsp;</p> <p><strong>Method read:</strong></p> <p>By using the <code>read4</code> method, implement the method read that reads <code>n</code> characters from <code>file</code> and store it in the buffer array <code>buf</code>. Consider that you cannot manipulate <code>file</code> directly.</p> <p>The return value is the number of actual characters read.</p> <p><strong>Definition of read: </strong></p> <pre> Parameters: char[] buf, int n Returns: int buf[] is a destination, not a source. You will need to write the results to buf[]. </pre> <p><strong>Note:</strong></p> <ul> <li>Consider that you cannot manipulate the file directly. The file is only accessible for <code>read4</code> but not for <code>read</code>.</li> <li>The read function may be <strong>called multiple times</strong>.</li> <li>Please remember to <strong>RESET</strong> your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see <a href="https://leetcode.com/faq/" target="_blank">here</a> for more details.</li> <li>You may assume the destination buffer array, <code>buf</code>, is guaranteed to have enough space for storing <code>n</code> characters.</li> <li>It is guaranteed that in a given test case the same buffer <code>buf</code> is called by <code>read</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, queries = [1,2,1] <strong>Output:</strong> [1,2,0] <strong>Explanation:</strong> The test case represents the following scenario: File file(&quot;abc&quot;); Solution sol; sol.read(buf, 1); // After calling your read method, buf should contain &quot;a&quot;. We read a total of 1 character from the file, so return 1. sol.read(buf, 2); // Now buf should contain &quot;bc&quot;. We read a total of 2 characters from the file, so return 2. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. Assume buf is allocated and guaranteed to have enough space for storing all characters from the file. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, queries = [4,1] <strong>Output:</strong> [3,0] <strong>Explanation:</strong> The test case represents the following scenario: File file(&quot;abc&quot;); Solution sol; sol.read(buf, 4); // After calling your read method, buf should contain &quot;abc&quot;. We read a total of 3 characters from the file, so return 3. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= file.length &lt;= 500</code></li> <li><code>file</code> consist of English letters and digits.</li> <li><code>1 &lt;= queries.length &lt;= 10</code></li> <li><code>1 &lt;= queries[i] &lt;= 500</code></li> </ul>
Array; Interactive; Simulation
Go
/** * The read4 API is already defined for you. * * read4 := func(buf4 []byte) int * * // Below is an example of how the read4 API can be called. * file := File("abcdefghijk") // File is "abcdefghijk", initially file pointer (fp) points to 'a' * buf4 := make([]byte, 4) // Create buffer with enough space to store characters * read4(buf4) // read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e' * read4(buf4) // read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i' * read4(buf4) // read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file */ var solution = func(read4 func([]byte) int) func([]byte, int) int { buf4 := make([]byte, 4) i, size := 0, 0 // implement read below. return func(buf []byte, n int) int { j := 0 for j < n { if i == size { size = read4(buf4) i = 0 if size == 0 { break } } for j < n && i < size { buf[j] = buf4[i] i, j = i+1, j+1 } } return j } }
158
Read N Characters Given read4 II - Call Multiple Times
Hard
<p>Given a <code>file</code> and assume that you can only read the file using a given method <code>read4</code>, implement a method <code>read</code> to read <code>n</code> characters. Your method <code>read</code> may be <strong>called multiple times</strong>.</p> <p><strong>Method read4: </strong></p> <p>The API <code>read4</code> reads <strong>four consecutive characters</strong> from <code>file</code>, then writes those characters into the buffer array <code>buf4</code>.</p> <p>The return value is the number of actual characters read.</p> <p>Note that <code>read4()</code> has its own file pointer, much like <code>FILE *fp</code> in C.</p> <p><strong>Definition of read4:</strong></p> <pre> Parameter: char[] buf4 Returns: int buf4[] is a destination, not a source. The results from read4 will be copied to buf4[]. </pre> <p>Below is a high-level example of how <code>read4</code> works:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0158.Read%20N%20Characters%20Given%20read4%20II%20-%20Call%20Multiple%20Times/images/157_example.png" style="width: 600px; height: 403px;" /> <pre> File file(&quot;abcde<code>&quot;); // File is &quot;</code>abcde<code>&quot;, initially file pointer (fp) points to &#39;a&#39; char[] buf4 = new char[4]; // Create buffer with enough space to store characters read4(buf4); // read4 returns 4. Now buf4 = &quot;abcd&quot;, fp points to &#39;e&#39; read4(buf4); // read4 returns 1. Now buf4 = &quot;e&quot;, fp points to end of file read4(buf4); // read4 returns 0. Now buf4 = &quot;&quot;, fp points to end of file</code> </pre> <p>&nbsp;</p> <p><strong>Method read:</strong></p> <p>By using the <code>read4</code> method, implement the method read that reads <code>n</code> characters from <code>file</code> and store it in the buffer array <code>buf</code>. Consider that you cannot manipulate <code>file</code> directly.</p> <p>The return value is the number of actual characters read.</p> <p><strong>Definition of read: </strong></p> <pre> Parameters: char[] buf, int n Returns: int buf[] is a destination, not a source. You will need to write the results to buf[]. </pre> <p><strong>Note:</strong></p> <ul> <li>Consider that you cannot manipulate the file directly. The file is only accessible for <code>read4</code> but not for <code>read</code>.</li> <li>The read function may be <strong>called multiple times</strong>.</li> <li>Please remember to <strong>RESET</strong> your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see <a href="https://leetcode.com/faq/" target="_blank">here</a> for more details.</li> <li>You may assume the destination buffer array, <code>buf</code>, is guaranteed to have enough space for storing <code>n</code> characters.</li> <li>It is guaranteed that in a given test case the same buffer <code>buf</code> is called by <code>read</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, queries = [1,2,1] <strong>Output:</strong> [1,2,0] <strong>Explanation:</strong> The test case represents the following scenario: File file(&quot;abc&quot;); Solution sol; sol.read(buf, 1); // After calling your read method, buf should contain &quot;a&quot;. We read a total of 1 character from the file, so return 1. sol.read(buf, 2); // Now buf should contain &quot;bc&quot;. We read a total of 2 characters from the file, so return 2. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. Assume buf is allocated and guaranteed to have enough space for storing all characters from the file. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, queries = [4,1] <strong>Output:</strong> [3,0] <strong>Explanation:</strong> The test case represents the following scenario: File file(&quot;abc&quot;); Solution sol; sol.read(buf, 4); // After calling your read method, buf should contain &quot;abc&quot;. We read a total of 3 characters from the file, so return 3. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= file.length &lt;= 500</code></li> <li><code>file</code> consist of English letters and digits.</li> <li><code>1 &lt;= queries.length &lt;= 10</code></li> <li><code>1 &lt;= queries[i] &lt;= 500</code></li> </ul>
Array; Interactive; Simulation
Java
/** * The read4 API is defined in the parent class Reader4. * int read4(char[] buf4); */ public class Solution extends Reader4 { private char[] buf4 = new char[4]; private int i; private int size; /** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */ public int read(char[] buf, int n) { int j = 0; while (j < n) { if (i == size) { size = read4(buf4); i = 0; if (size == 0) { break; } } while (j < n && i < size) { buf[j++] = buf4[i++]; } } return j; } }
158
Read N Characters Given read4 II - Call Multiple Times
Hard
<p>Given a <code>file</code> and assume that you can only read the file using a given method <code>read4</code>, implement a method <code>read</code> to read <code>n</code> characters. Your method <code>read</code> may be <strong>called multiple times</strong>.</p> <p><strong>Method read4: </strong></p> <p>The API <code>read4</code> reads <strong>four consecutive characters</strong> from <code>file</code>, then writes those characters into the buffer array <code>buf4</code>.</p> <p>The return value is the number of actual characters read.</p> <p>Note that <code>read4()</code> has its own file pointer, much like <code>FILE *fp</code> in C.</p> <p><strong>Definition of read4:</strong></p> <pre> Parameter: char[] buf4 Returns: int buf4[] is a destination, not a source. The results from read4 will be copied to buf4[]. </pre> <p>Below is a high-level example of how <code>read4</code> works:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0158.Read%20N%20Characters%20Given%20read4%20II%20-%20Call%20Multiple%20Times/images/157_example.png" style="width: 600px; height: 403px;" /> <pre> File file(&quot;abcde<code>&quot;); // File is &quot;</code>abcde<code>&quot;, initially file pointer (fp) points to &#39;a&#39; char[] buf4 = new char[4]; // Create buffer with enough space to store characters read4(buf4); // read4 returns 4. Now buf4 = &quot;abcd&quot;, fp points to &#39;e&#39; read4(buf4); // read4 returns 1. Now buf4 = &quot;e&quot;, fp points to end of file read4(buf4); // read4 returns 0. Now buf4 = &quot;&quot;, fp points to end of file</code> </pre> <p>&nbsp;</p> <p><strong>Method read:</strong></p> <p>By using the <code>read4</code> method, implement the method read that reads <code>n</code> characters from <code>file</code> and store it in the buffer array <code>buf</code>. Consider that you cannot manipulate <code>file</code> directly.</p> <p>The return value is the number of actual characters read.</p> <p><strong>Definition of read: </strong></p> <pre> Parameters: char[] buf, int n Returns: int buf[] is a destination, not a source. You will need to write the results to buf[]. </pre> <p><strong>Note:</strong></p> <ul> <li>Consider that you cannot manipulate the file directly. The file is only accessible for <code>read4</code> but not for <code>read</code>.</li> <li>The read function may be <strong>called multiple times</strong>.</li> <li>Please remember to <strong>RESET</strong> your class variables declared in Solution, as static/class variables are persisted across multiple test cases. Please see <a href="https://leetcode.com/faq/" target="_blank">here</a> for more details.</li> <li>You may assume the destination buffer array, <code>buf</code>, is guaranteed to have enough space for storing <code>n</code> characters.</li> <li>It is guaranteed that in a given test case the same buffer <code>buf</code> is called by <code>read</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, queries = [1,2,1] <strong>Output:</strong> [1,2,0] <strong>Explanation:</strong> The test case represents the following scenario: File file(&quot;abc&quot;); Solution sol; sol.read(buf, 1); // After calling your read method, buf should contain &quot;a&quot;. We read a total of 1 character from the file, so return 1. sol.read(buf, 2); // Now buf should contain &quot;bc&quot;. We read a total of 2 characters from the file, so return 2. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. Assume buf is allocated and guaranteed to have enough space for storing all characters from the file. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> file = &quot;abc&quot;, queries = [4,1] <strong>Output:</strong> [3,0] <strong>Explanation:</strong> The test case represents the following scenario: File file(&quot;abc&quot;); Solution sol; sol.read(buf, 4); // After calling your read method, buf should contain &quot;abc&quot;. We read a total of 3 characters from the file, so return 3. sol.read(buf, 1); // We have reached the end of file, no more characters can be read. So return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= file.length &lt;= 500</code></li> <li><code>file</code> consist of English letters and digits.</li> <li><code>1 &lt;= queries.length &lt;= 10</code></li> <li><code>1 &lt;= queries[i] &lt;= 500</code></li> </ul>
Array; Interactive; Simulation
Python
# The read4 API is already defined for you. # def read4(buf4: List[str]) -> int: class Solution: def __init__(self): self.buf4 = [None] * 4 self.i = self.size = 0 def read(self, buf: List[str], n: int) -> int: j = 0 while j < n: if self.i == self.size: self.size = read4(self.buf4) self.i = 0 if self.size == 0: break while j < n and self.i < self.size: buf[j] = self.buf4[self.i] self.i += 1 j += 1 return j
159
Longest Substring with At Most Two Distinct Characters
Medium
<p>Given a string <code>s</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> that contains at most <strong>two distinct characters</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; which its length is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ccaabbb&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The substring is &quot;aabbb&quot; which its length is 5. </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</code> consists of English letters.</li> </ul>
Hash Table; String; Sliding Window
C++
class Solution { public: int lengthOfLongestSubstringTwoDistinct(string s) { unordered_map<char, int> cnt; int n = s.size(); int ans = 0; for (int i = 0, j = 0; i < n; ++i) { cnt[s[i]]++; while (cnt.size() > 2) { cnt[s[j]]--; if (cnt[s[j]] == 0) { cnt.erase(s[j]); } ++j; } ans = max(ans, i - j + 1); } return ans; } };
159
Longest Substring with At Most Two Distinct Characters
Medium
<p>Given a string <code>s</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> that contains at most <strong>two distinct characters</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; which its length is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ccaabbb&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The substring is &quot;aabbb&quot; which its length is 5. </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</code> consists of English letters.</li> </ul>
Hash Table; String; Sliding Window
Go
func lengthOfLongestSubstringTwoDistinct(s string) (ans int) { cnt := map[byte]int{} j := 0 for i := range s { cnt[s[i]]++ for len(cnt) > 2 { cnt[s[j]]-- if cnt[s[j]] == 0 { delete(cnt, s[j]) } j++ } ans = max(ans, i-j+1) } return }
159
Longest Substring with At Most Two Distinct Characters
Medium
<p>Given a string <code>s</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> that contains at most <strong>two distinct characters</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; which its length is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ccaabbb&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The substring is &quot;aabbb&quot; which its length is 5. </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</code> consists of English letters.</li> </ul>
Hash Table; String; Sliding Window
Java
class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { Map<Character, Integer> cnt = new HashMap<>(); int n = s.length(); int ans = 0; for (int i = 0, j = 0; i < n; ++i) { char c = s.charAt(i); cnt.put(c, cnt.getOrDefault(c, 0) + 1); while (cnt.size() > 2) { char t = s.charAt(j++); cnt.put(t, cnt.get(t) - 1); if (cnt.get(t) == 0) { cnt.remove(t); } } ans = Math.max(ans, i - j + 1); } return ans; } }
159
Longest Substring with At Most Two Distinct Characters
Medium
<p>Given a string <code>s</code>, return <em>the length of the longest </em><span data-keyword="substring-nonempty"><em>substring</em></span><em> that contains at most <strong>two distinct characters</strong></em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;eceba&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> The substring is &quot;ece&quot; which its length is 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ccaabbb&quot; <strong>Output:</strong> 5 <strong>Explanation:</strong> The substring is &quot;aabbb&quot; which its length is 5. </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</code> consists of English letters.</li> </ul>
Hash Table; String; Sliding Window
Python
class Solution: def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int: cnt = Counter() ans = j = 0 for i, c in enumerate(s): cnt[c] += 1 while len(cnt) > 2: cnt[s[j]] -= 1 if cnt[s[j]] == 0: cnt.pop(s[j]) j += 1 ans = max(ans, i - j + 1) return ans
160
Intersection of Two Linked Lists
Easy
<p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p> <p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_statement.png" style="width: 500px; height: 162px;" /> <p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p> <p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p> <p><strong>Custom Judge:</strong></p> <p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p> <ul> <li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li> <li><code>listA</code> - The first linked list.</li> <li><code>listB</code> - The second linked list.</li> <li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li> <li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li> </ul> <p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_1_1.png" style="width: 500px; height: 162px;" /> <pre> <strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 <strong>Output:</strong> Intersected at &#39;8&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node&#39;s value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_2.png" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 <strong>Output:</strong> Intersected at &#39;2&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_3.png" style="width: 300px; height: 189px;" /> <pre> <strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 <strong>Output:</strong> No intersection <strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li> <li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li> <li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= skipA &lt;= m</code></li> <li><code>0 &lt;= skipB &lt;= n</code></li> <li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li> <li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?
Hash Table; Linked List; Two Pointers
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) { ListNode *a = headA, *b = headB; while (a != b) { a = a ? a->next : headB; b = b ? b->next : headA; } return a; } };
160
Intersection of Two Linked Lists
Easy
<p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p> <p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_statement.png" style="width: 500px; height: 162px;" /> <p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p> <p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p> <p><strong>Custom Judge:</strong></p> <p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p> <ul> <li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li> <li><code>listA</code> - The first linked list.</li> <li><code>listB</code> - The second linked list.</li> <li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li> <li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li> </ul> <p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_1_1.png" style="width: 500px; height: 162px;" /> <pre> <strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 <strong>Output:</strong> Intersected at &#39;8&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node&#39;s value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_2.png" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 <strong>Output:</strong> Intersected at &#39;2&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_3.png" style="width: 300px; height: 189px;" /> <pre> <strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 <strong>Output:</strong> No intersection <strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li> <li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li> <li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= skipA &lt;= m</code></li> <li><code>0 &lt;= skipB &lt;= n</code></li> <li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li> <li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?
Hash Table; Linked List; Two Pointers
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func getIntersectionNode(headA, headB *ListNode) *ListNode { a, b := headA, headB for a != b { if a == nil { a = headB } else { a = a.Next } if b == nil { b = headA } else { b = b.Next } } return a }
160
Intersection of Two Linked Lists
Easy
<p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p> <p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_statement.png" style="width: 500px; height: 162px;" /> <p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p> <p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p> <p><strong>Custom Judge:</strong></p> <p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p> <ul> <li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li> <li><code>listA</code> - The first linked list.</li> <li><code>listB</code> - The second linked list.</li> <li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li> <li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li> </ul> <p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_1_1.png" style="width: 500px; height: 162px;" /> <pre> <strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 <strong>Output:</strong> Intersected at &#39;8&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node&#39;s value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_2.png" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 <strong>Output:</strong> Intersected at &#39;2&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_3.png" style="width: 300px; height: 189px;" /> <pre> <strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 <strong>Output:</strong> No intersection <strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li> <li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li> <li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= skipA &lt;= m</code></li> <li><code>0 &lt;= skipB &lt;= n</code></li> <li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li> <li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?
Hash Table; Linked List; Two Pointers
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode a = headA, b = headB; while (a != b) { a = a == null ? headB : a.next; b = b == null ? headA : b.next; } return a; } }
160
Intersection of Two Linked Lists
Easy
<p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p> <p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_statement.png" style="width: 500px; height: 162px;" /> <p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p> <p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p> <p><strong>Custom Judge:</strong></p> <p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p> <ul> <li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li> <li><code>listA</code> - The first linked list.</li> <li><code>listB</code> - The second linked list.</li> <li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li> <li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li> </ul> <p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_1_1.png" style="width: 500px; height: 162px;" /> <pre> <strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 <strong>Output:</strong> Intersected at &#39;8&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node&#39;s value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_2.png" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 <strong>Output:</strong> Intersected at &#39;2&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_3.png" style="width: 300px; height: 189px;" /> <pre> <strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 <strong>Output:</strong> No intersection <strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li> <li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li> <li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= skipA &lt;= m</code></li> <li><code>0 &lt;= skipB &lt;= n</code></li> <li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li> <li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?
Hash Table; Linked List; Two Pointers
JavaScript
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} headA * @param {ListNode} headB * @return {ListNode} */ var getIntersectionNode = function (headA, headB) { let [a, b] = [headA, headB]; while (a !== b) { a = a ? a.next : headB; b = b ? b.next : headA; } return a; };
160
Intersection of Two Linked Lists
Easy
<p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p> <p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_statement.png" style="width: 500px; height: 162px;" /> <p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p> <p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p> <p><strong>Custom Judge:</strong></p> <p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p> <ul> <li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li> <li><code>listA</code> - The first linked list.</li> <li><code>listB</code> - The second linked list.</li> <li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li> <li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li> </ul> <p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_1_1.png" style="width: 500px; height: 162px;" /> <pre> <strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 <strong>Output:</strong> Intersected at &#39;8&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node&#39;s value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_2.png" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 <strong>Output:</strong> Intersected at &#39;2&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_3.png" style="width: 300px; height: 189px;" /> <pre> <strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 <strong>Output:</strong> No intersection <strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li> <li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li> <li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= skipA &lt;= m</code></li> <li><code>0 &lt;= skipB &lt;= n</code></li> <li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li> <li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?
Hash Table; Linked List; Two Pointers
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: a, b = headA, headB while a != b: a = a.next if a else headB b = b.next if b else headA return a
160
Intersection of Two Linked Lists
Easy
<p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p> <p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_statement.png" style="width: 500px; height: 162px;" /> <p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p> <p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p> <p><strong>Custom Judge:</strong></p> <p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p> <ul> <li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li> <li><code>listA</code> - The first linked list.</li> <li><code>listB</code> - The second linked list.</li> <li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li> <li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li> </ul> <p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_1_1.png" style="width: 500px; height: 162px;" /> <pre> <strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 <strong>Output:</strong> Intersected at &#39;8&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node&#39;s value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_2.png" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 <strong>Output:</strong> Intersected at &#39;2&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_3.png" style="width: 300px; height: 189px;" /> <pre> <strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 <strong>Output:</strong> No intersection <strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li> <li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li> <li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= skipA &lt;= m</code></li> <li><code>0 &lt;= skipB &lt;= n</code></li> <li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li> <li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?
Hash Table; Linked List; Two Pointers
Swift
/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class Solution { func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? { var a = headA var b = headB while a !== b { a = a == nil ? headB : a?.next b = b == nil ? headA : b?.next } return a } }
160
Intersection of Two Linked Lists
Easy
<p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p> <p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_statement.png" style="width: 500px; height: 162px;" /> <p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p> <p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p> <p><strong>Custom Judge:</strong></p> <p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p> <ul> <li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li> <li><code>listA</code> - The first linked list.</li> <li><code>listB</code> - The second linked list.</li> <li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li> <li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li> </ul> <p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_1_1.png" style="width: 500px; height: 162px;" /> <pre> <strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 <strong>Output:</strong> Intersected at &#39;8&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node&#39;s value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_2.png" style="width: 500px; height: 194px;" /> <pre> <strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 <strong>Output:</strong> Intersected at &#39;2&#39; <strong>Explanation:</strong> The intersected node&#39;s value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/images/160_example_3.png" style="width: 300px; height: 189px;" /> <pre> <strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 <strong>Output:</strong> No intersection <strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li> <li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li> <li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li> <li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= skipA &lt;= m</code></li> <li><code>0 &lt;= skipB &lt;= n</code></li> <li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li> <li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?
Hash Table; Linked List; Two Pointers
TypeScript
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { let [a, b] = [headA, headB]; while (a !== b) { a = a ? a.next : headB; b = b ? b.next : headA; } return a; }
161
One Edit Distance
Medium
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if they are both one edit distance apart, otherwise return <code>false</code>.</p> <p>A string <code>s</code> is said to be one distance apart from a string <code>t</code> if you can:</p> <ul> <li>Insert <strong>exactly one</strong> character into <code>s</code> to get <code>t</code>.</li> <li>Delete <strong>exactly one</strong> character from <code>s</code> to get <code>t</code>.</li> <li>Replace <strong>exactly one</strong> character of <code>s</code> with <strong>a different character</strong> to get <code>t</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, t = &quot;acb&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can insert &#39;c&#39; into s&nbsp;to get&nbsp;t. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> We cannot get t from s by only one step. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase letters, uppercase letters, and digits.</li> </ul>
Two Pointers; String
C++
class Solution { public: bool isOneEditDistance(string s, string t) { int m = s.size(), n = t.size(); if (m < n) return isOneEditDistance(t, s); if (m - n > 1) return false; for (int i = 0; i < n; ++i) { if (s[i] != t[i]) { if (m == n) return s.substr(i + 1) == t.substr(i + 1); return s.substr(i + 1) == t.substr(i); } } return m == n + 1; } };
161
One Edit Distance
Medium
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if they are both one edit distance apart, otherwise return <code>false</code>.</p> <p>A string <code>s</code> is said to be one distance apart from a string <code>t</code> if you can:</p> <ul> <li>Insert <strong>exactly one</strong> character into <code>s</code> to get <code>t</code>.</li> <li>Delete <strong>exactly one</strong> character from <code>s</code> to get <code>t</code>.</li> <li>Replace <strong>exactly one</strong> character of <code>s</code> with <strong>a different character</strong> to get <code>t</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, t = &quot;acb&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can insert &#39;c&#39; into s&nbsp;to get&nbsp;t. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> We cannot get t from s by only one step. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase letters, uppercase letters, and digits.</li> </ul>
Two Pointers; String
Go
func isOneEditDistance(s string, t string) bool { m, n := len(s), len(t) if m < n { return isOneEditDistance(t, s) } if m-n > 1 { return false } for i := range t { if s[i] != t[i] { if m == n { return s[i+1:] == t[i+1:] } return s[i+1:] == t[i:] } } return m == n+1 }
161
One Edit Distance
Medium
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if they are both one edit distance apart, otherwise return <code>false</code>.</p> <p>A string <code>s</code> is said to be one distance apart from a string <code>t</code> if you can:</p> <ul> <li>Insert <strong>exactly one</strong> character into <code>s</code> to get <code>t</code>.</li> <li>Delete <strong>exactly one</strong> character from <code>s</code> to get <code>t</code>.</li> <li>Replace <strong>exactly one</strong> character of <code>s</code> with <strong>a different character</strong> to get <code>t</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, t = &quot;acb&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can insert &#39;c&#39; into s&nbsp;to get&nbsp;t. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> We cannot get t from s by only one step. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase letters, uppercase letters, and digits.</li> </ul>
Two Pointers; String
Java
class Solution { public boolean isOneEditDistance(String s, String t) { int m = s.length(), n = t.length(); if (m < n) { return isOneEditDistance(t, s); } if (m - n > 1) { return false; } for (int i = 0; i < n; ++i) { if (s.charAt(i) != t.charAt(i)) { if (m == n) { return s.substring(i + 1).equals(t.substring(i + 1)); } return s.substring(i + 1).equals(t.substring(i)); } } return m == n + 1; } }
161
One Edit Distance
Medium
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if they are both one edit distance apart, otherwise return <code>false</code>.</p> <p>A string <code>s</code> is said to be one distance apart from a string <code>t</code> if you can:</p> <ul> <li>Insert <strong>exactly one</strong> character into <code>s</code> to get <code>t</code>.</li> <li>Delete <strong>exactly one</strong> character from <code>s</code> to get <code>t</code>.</li> <li>Replace <strong>exactly one</strong> character of <code>s</code> with <strong>a different character</strong> to get <code>t</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, t = &quot;acb&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can insert &#39;c&#39; into s&nbsp;to get&nbsp;t. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> We cannot get t from s by only one step. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase letters, uppercase letters, and digits.</li> </ul>
Two Pointers; String
Python
class Solution: def isOneEditDistance(self, s: str, t: str) -> bool: if len(s) < len(t): return self.isOneEditDistance(t, s) m, n = len(s), len(t) if m - n > 1: return False for i, c in enumerate(t): if c != s[i]: return s[i + 1 :] == t[i + 1 :] if m == n else s[i + 1 :] == t[i:] return m == n + 1
161
One Edit Distance
Medium
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if they are both one edit distance apart, otherwise return <code>false</code>.</p> <p>A string <code>s</code> is said to be one distance apart from a string <code>t</code> if you can:</p> <ul> <li>Insert <strong>exactly one</strong> character into <code>s</code> to get <code>t</code>.</li> <li>Delete <strong>exactly one</strong> character from <code>s</code> to get <code>t</code>.</li> <li>Replace <strong>exactly one</strong> character of <code>s</code> with <strong>a different character</strong> to get <code>t</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, t = &quot;acb&quot; <strong>Output:</strong> true <strong>Explanation:</strong> We can insert &#39;c&#39; into s&nbsp;to get&nbsp;t. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;&quot; <strong>Output:</strong> false <strong>Explanation:</strong> We cannot get t from s by only one step. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length, t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist of lowercase letters, uppercase letters, and digits.</li> </ul>
Two Pointers; String
TypeScript
function isOneEditDistance(s: string, t: string): boolean { const [m, n] = [s.length, t.length]; if (m < n) { return isOneEditDistance(t, s); } if (m - n > 1) { return false; } for (let i = 0; i < n; ++i) { if (s[i] !== t[i]) { return s.slice(i + 1) === t.slice(i + (m === n ? 1 : 0)); } } return m === n + 1; }
162
Find Peak Element
Medium
<p>A peak element is an element that is strictly greater than its neighbors.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, find a peak element, and return its index. If the array contains multiple peaks, return the index to <strong>any of the peaks</strong>.</p> <p>You may imagine that <code>nums[-1] = nums[n] = -&infin;</code>. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.</p> <p>You must write an algorithm that runs in <code>O(log n)</code> time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 3 is a peak element and your function should return the index number 2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>nums[i] != nums[i + 1]</code> for all valid <code>i</code>.</li> </ul>
Array; Binary Search
C++
class Solution { public: int findPeakElement(vector<int>& nums) { int left = 0, right = nums.size() - 1; while (left < right) { int mid = left + right >> 1; if (nums[mid] > nums[mid + 1]) { right = mid; } else { left = mid + 1; } } return left; } };
162
Find Peak Element
Medium
<p>A peak element is an element that is strictly greater than its neighbors.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, find a peak element, and return its index. If the array contains multiple peaks, return the index to <strong>any of the peaks</strong>.</p> <p>You may imagine that <code>nums[-1] = nums[n] = -&infin;</code>. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.</p> <p>You must write an algorithm that runs in <code>O(log n)</code> time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 3 is a peak element and your function should return the index number 2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>nums[i] != nums[i + 1]</code> for all valid <code>i</code>.</li> </ul>
Array; Binary Search
Go
func findPeakElement(nums []int) int { left, right := 0, len(nums)-1 for left < right { mid := (left + right) >> 1 if nums[mid] > nums[mid+1] { right = mid } else { left = mid + 1 } } return left }
162
Find Peak Element
Medium
<p>A peak element is an element that is strictly greater than its neighbors.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, find a peak element, and return its index. If the array contains multiple peaks, return the index to <strong>any of the peaks</strong>.</p> <p>You may imagine that <code>nums[-1] = nums[n] = -&infin;</code>. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.</p> <p>You must write an algorithm that runs in <code>O(log n)</code> time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 3 is a peak element and your function should return the index number 2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>nums[i] != nums[i + 1]</code> for all valid <code>i</code>.</li> </ul>
Array; Binary Search
Java
class Solution { public int findPeakElement(int[] nums) { int left = 0, right = nums.length - 1; while (left < right) { int mid = (left + right) >> 1; if (nums[mid] > nums[mid + 1]) { right = mid; } else { left = mid + 1; } } return left; } }
162
Find Peak Element
Medium
<p>A peak element is an element that is strictly greater than its neighbors.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, find a peak element, and return its index. If the array contains multiple peaks, return the index to <strong>any of the peaks</strong>.</p> <p>You may imagine that <code>nums[-1] = nums[n] = -&infin;</code>. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.</p> <p>You must write an algorithm that runs in <code>O(log n)</code> time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 3 is a peak element and your function should return the index number 2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>nums[i] != nums[i + 1]</code> for all valid <code>i</code>.</li> </ul>
Array; Binary Search
Python
class Solution: def findPeakElement(self, nums: List[int]) -> int: left, right = 0, len(nums) - 1 while left < right: mid = (left + right) >> 1 if nums[mid] > nums[mid + 1]: right = mid else: left = mid + 1 return left
162
Find Peak Element
Medium
<p>A peak element is an element that is strictly greater than its neighbors.</p> <p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, find a peak element, and return its index. If the array contains multiple peaks, return the index to <strong>any of the peaks</strong>.</p> <p>You may imagine that <code>nums[-1] = nums[n] = -&infin;</code>. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.</p> <p>You must write an algorithm that runs in <code>O(log n)</code> time.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,3,1] <strong>Output:</strong> 2 <strong>Explanation:</strong> 3 is a peak element and your function should return the index number 2.</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [1,2,1,3,5,6,4] <strong>Output:</strong> 5 <strong>Explanation:</strong> Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.</pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>nums[i] != nums[i + 1]</code> for all valid <code>i</code>.</li> </ul>
Array; Binary Search
TypeScript
function findPeakElement(nums: number[]): number { let [left, right] = [0, nums.length - 1]; while (left < right) { const mid = (left + right) >> 1; if (nums[mid] > nums[mid + 1]) { right = mid; } else { left = mid + 1; } } return left; }
163
Missing Ranges
Easy
<p>You are given an inclusive range <code>[lower, upper]</code> and a <strong>sorted unique</strong> integer array <code>nums</code>, where all elements are within the inclusive range.</p> <p>A number <code>x</code> is considered <strong>missing</strong> if <code>x</code> is in the range <code>[lower, upper]</code> and <code>x</code> is not in <code>nums</code>.</p> <p>Return <em>the <strong>shortest sorted</strong> list of ranges that <b>exactly covers all the missing numbers</b></em>. That is, no element of <code>nums</code> is included in any of the ranges, and each missing number is covered by one of the ranges.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,3,50,75], lower = 0, upper = 99 <strong>Output:</strong> [[2,2],[4,49],[51,74],[76,99]] <strong>Explanation:</strong> The ranges are: [2,2] [4,49] [51,74] [76,99] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1], lower = -1, upper = -1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no missing ranges since there are no missing numbers. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>9</sup> &lt;= lower &lt;= upper &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>lower &lt;= nums[i] &lt;= upper</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array
C++
class Solution { public: vector<vector<int>> findMissingRanges(vector<int>& nums, int lower, int upper) { int n = nums.size(); if (n == 0) { return {{lower, upper}}; } vector<vector<int>> ans; if (nums[0] > lower) { ans.push_back({lower, nums[0] - 1}); } for (int i = 1; i < nums.size(); ++i) { if (nums[i] - nums[i - 1] > 1) { ans.push_back({nums[i - 1] + 1, nums[i] - 1}); } } if (nums[n - 1] < upper) { ans.push_back({nums[n - 1] + 1, upper}); } return ans; } };
163
Missing Ranges
Easy
<p>You are given an inclusive range <code>[lower, upper]</code> and a <strong>sorted unique</strong> integer array <code>nums</code>, where all elements are within the inclusive range.</p> <p>A number <code>x</code> is considered <strong>missing</strong> if <code>x</code> is in the range <code>[lower, upper]</code> and <code>x</code> is not in <code>nums</code>.</p> <p>Return <em>the <strong>shortest sorted</strong> list of ranges that <b>exactly covers all the missing numbers</b></em>. That is, no element of <code>nums</code> is included in any of the ranges, and each missing number is covered by one of the ranges.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,3,50,75], lower = 0, upper = 99 <strong>Output:</strong> [[2,2],[4,49],[51,74],[76,99]] <strong>Explanation:</strong> The ranges are: [2,2] [4,49] [51,74] [76,99] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1], lower = -1, upper = -1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no missing ranges since there are no missing numbers. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>9</sup> &lt;= lower &lt;= upper &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>lower &lt;= nums[i] &lt;= upper</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array
Go
func findMissingRanges(nums []int, lower int, upper int) (ans [][]int) { n := len(nums) if n == 0 { return [][]int{{lower, upper}} } if nums[0] > lower { ans = append(ans, []int{lower, nums[0] - 1}) } for i, b := range nums[1:] { if a := nums[i]; b-a > 1 { ans = append(ans, []int{a + 1, b - 1}) } } if nums[n-1] < upper { ans = append(ans, []int{nums[n-1] + 1, upper}) } return }
163
Missing Ranges
Easy
<p>You are given an inclusive range <code>[lower, upper]</code> and a <strong>sorted unique</strong> integer array <code>nums</code>, where all elements are within the inclusive range.</p> <p>A number <code>x</code> is considered <strong>missing</strong> if <code>x</code> is in the range <code>[lower, upper]</code> and <code>x</code> is not in <code>nums</code>.</p> <p>Return <em>the <strong>shortest sorted</strong> list of ranges that <b>exactly covers all the missing numbers</b></em>. That is, no element of <code>nums</code> is included in any of the ranges, and each missing number is covered by one of the ranges.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,3,50,75], lower = 0, upper = 99 <strong>Output:</strong> [[2,2],[4,49],[51,74],[76,99]] <strong>Explanation:</strong> The ranges are: [2,2] [4,49] [51,74] [76,99] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1], lower = -1, upper = -1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no missing ranges since there are no missing numbers. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>9</sup> &lt;= lower &lt;= upper &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>lower &lt;= nums[i] &lt;= upper</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array
Java
class Solution { public List<List<Integer>> findMissingRanges(int[] nums, int lower, int upper) { int n = nums.length; if (n == 0) { return List.of(List.of(lower, upper)); } List<List<Integer>> ans = new ArrayList<>(); if (nums[0] > lower) { ans.add(List.of(lower, nums[0] - 1)); } for (int i = 1; i < n; ++i) { if (nums[i] - nums[i - 1] > 1) { ans.add(List.of(nums[i - 1] + 1, nums[i] - 1)); } } if (nums[n - 1] < upper) { ans.add(List.of(nums[n - 1] + 1, upper)); } return ans; } }
163
Missing Ranges
Easy
<p>You are given an inclusive range <code>[lower, upper]</code> and a <strong>sorted unique</strong> integer array <code>nums</code>, where all elements are within the inclusive range.</p> <p>A number <code>x</code> is considered <strong>missing</strong> if <code>x</code> is in the range <code>[lower, upper]</code> and <code>x</code> is not in <code>nums</code>.</p> <p>Return <em>the <strong>shortest sorted</strong> list of ranges that <b>exactly covers all the missing numbers</b></em>. That is, no element of <code>nums</code> is included in any of the ranges, and each missing number is covered by one of the ranges.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,3,50,75], lower = 0, upper = 99 <strong>Output:</strong> [[2,2],[4,49],[51,74],[76,99]] <strong>Explanation:</strong> The ranges are: [2,2] [4,49] [51,74] [76,99] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1], lower = -1, upper = -1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no missing ranges since there are no missing numbers. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>9</sup> &lt;= lower &lt;= upper &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>lower &lt;= nums[i] &lt;= upper</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array
Python
class Solution: def findMissingRanges( self, nums: List[int], lower: int, upper: int ) -> List[List[int]]: n = len(nums) if n == 0: return [[lower, upper]] ans = [] if nums[0] > lower: ans.append([lower, nums[0] - 1]) for a, b in pairwise(nums): if b - a > 1: ans.append([a + 1, b - 1]) if nums[-1] < upper: ans.append([nums[-1] + 1, upper]) return ans
163
Missing Ranges
Easy
<p>You are given an inclusive range <code>[lower, upper]</code> and a <strong>sorted unique</strong> integer array <code>nums</code>, where all elements are within the inclusive range.</p> <p>A number <code>x</code> is considered <strong>missing</strong> if <code>x</code> is in the range <code>[lower, upper]</code> and <code>x</code> is not in <code>nums</code>.</p> <p>Return <em>the <strong>shortest sorted</strong> list of ranges that <b>exactly covers all the missing numbers</b></em>. That is, no element of <code>nums</code> is included in any of the ranges, and each missing number is covered by one of the ranges.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,3,50,75], lower = 0, upper = 99 <strong>Output:</strong> [[2,2],[4,49],[51,74],[76,99]] <strong>Explanation:</strong> The ranges are: [2,2] [4,49] [51,74] [76,99] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [-1], lower = -1, upper = -1 <strong>Output:</strong> [] <strong>Explanation:</strong> There are no missing ranges since there are no missing numbers. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>9</sup> &lt;= lower &lt;= upper &lt;= 10<sup>9</sup></code></li> <li><code>0 &lt;= nums.length &lt;= 100</code></li> <li><code>lower &lt;= nums[i] &lt;= upper</code></li> <li>All the values of <code>nums</code> are <strong>unique</strong>.</li> </ul>
Array
TypeScript
function findMissingRanges(nums: number[], lower: number, upper: number): number[][] { const n = nums.length; if (n === 0) { return [[lower, upper]]; } const ans: number[][] = []; if (nums[0] > lower) { ans.push([lower, nums[0] - 1]); } for (let i = 1; i < n; ++i) { if (nums[i] - nums[i - 1] > 1) { ans.push([nums[i - 1] + 1, nums[i] - 1]); } } if (nums[n - 1] < upper) { ans.push([nums[n - 1] + 1, upper]); } return ans; }
164
Maximum Gap
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum difference between two successive elements in its sorted form</em>. If the array contains less than two elements, return <code>0</code>.</p> <p>You must write an algorithm that runs in linear time and uses linear extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,6,9,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10] <strong>Output:</strong> 0 <strong>Explanation:</strong> The array contains less than 2 elements, therefore return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Radix Sort; Sorting
C++
using pii = pair<int, int>; class Solution { public: const int inf = 0x3f3f3f3f; int maximumGap(vector<int>& nums) { int n = nums.size(); if (n < 2) return 0; int mi = inf, mx = -inf; for (int v : nums) { mi = min(mi, v); mx = max(mx, v); } int bucketSize = max(1, (mx - mi) / (n - 1)); int bucketCount = (mx - mi) / bucketSize + 1; vector<pii> buckets(bucketCount, {inf, -inf}); for (int v : nums) { int i = (v - mi) / bucketSize; buckets[i].first = min(buckets[i].first, v); buckets[i].second = max(buckets[i].second, v); } int ans = 0; int prev = inf; for (auto [curmin, curmax] : buckets) { if (curmin > curmax) continue; ans = max(ans, curmin - prev); prev = curmax; } return ans; } };
164
Maximum Gap
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum difference between two successive elements in its sorted form</em>. If the array contains less than two elements, return <code>0</code>.</p> <p>You must write an algorithm that runs in linear time and uses linear extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,6,9,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10] <strong>Output:</strong> 0 <strong>Explanation:</strong> The array contains less than 2 elements, therefore return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Radix Sort; Sorting
C#
using System; using System.Linq; public class Solution { public int MaximumGap(int[] nums) { if (nums.Length < 2) return 0; var max = nums.Max(); var min = nums.Min(); var bucketSize = Math.Max(1, (max - min) / (nums.Length - 1)); var buckets = new Tuple<int, int>[(max - min) / bucketSize + 1]; foreach (var num in nums) { var index = (num - min) / bucketSize; if (buckets[index] == null) { buckets[index] = Tuple.Create(num, num); } else { buckets[index] = Tuple.Create(Math.Min(buckets[index].Item1, num), Math.Max(buckets[index].Item2, num)); } } var result = 0; Tuple<int, int> lastBucket = null; for (var i = 0; i < buckets.Length; ++i) { if (buckets[i] != null) { if (lastBucket != null) { result = Math.Max(result, buckets[i].Item1 - lastBucket.Item2); } lastBucket = buckets[i]; } } return result; } }
164
Maximum Gap
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum difference between two successive elements in its sorted form</em>. If the array contains less than two elements, return <code>0</code>.</p> <p>You must write an algorithm that runs in linear time and uses linear extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,6,9,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10] <strong>Output:</strong> 0 <strong>Explanation:</strong> The array contains less than 2 elements, therefore return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Radix Sort; Sorting
Go
func maximumGap(nums []int) int { n := len(nums) if n < 2 { return 0 } inf := 0x3f3f3f3f mi, mx := inf, -inf for _, v := range nums { mi = min(mi, v) mx = max(mx, v) } bucketSize := max(1, (mx-mi)/(n-1)) bucketCount := (mx-mi)/bucketSize + 1 buckets := make([][]int, bucketCount) for i := range buckets { buckets[i] = []int{inf, -inf} } for _, v := range nums { i := (v - mi) / bucketSize buckets[i][0] = min(buckets[i][0], v) buckets[i][1] = max(buckets[i][1], v) } ans := 0 prev := inf for _, bucket := range buckets { if bucket[0] > bucket[1] { continue } ans = max(ans, bucket[0]-prev) prev = bucket[1] } return ans }
164
Maximum Gap
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum difference between two successive elements in its sorted form</em>. If the array contains less than two elements, return <code>0</code>.</p> <p>You must write an algorithm that runs in linear time and uses linear extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,6,9,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10] <strong>Output:</strong> 0 <strong>Explanation:</strong> The array contains less than 2 elements, therefore return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Radix Sort; Sorting
Java
class Solution { public int maximumGap(int[] nums) { int n = nums.length; if (n < 2) { return 0; } int inf = 0x3f3f3f3f; int mi = inf, mx = -inf; for (int v : nums) { mi = Math.min(mi, v); mx = Math.max(mx, v); } int bucketSize = Math.max(1, (mx - mi) / (n - 1)); int bucketCount = (mx - mi) / bucketSize + 1; int[][] buckets = new int[bucketCount][2]; for (var bucket : buckets) { bucket[0] = inf; bucket[1] = -inf; } for (int v : nums) { int i = (v - mi) / bucketSize; buckets[i][0] = Math.min(buckets[i][0], v); buckets[i][1] = Math.max(buckets[i][1], v); } int prev = inf; int ans = 0; for (var bucket : buckets) { if (bucket[0] > bucket[1]) { continue; } ans = Math.max(ans, bucket[0] - prev); prev = bucket[1]; } return ans; } }
164
Maximum Gap
Medium
<p>Given an integer array <code>nums</code>, return <em>the maximum difference between two successive elements in its sorted form</em>. If the array contains less than two elements, return <code>0</code>.</p> <p>You must write an algorithm that runs in linear time and uses linear extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [3,6,9,1] <strong>Output:</strong> 3 <strong>Explanation:</strong> The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [10] <strong>Output:</strong> 0 <strong>Explanation:</strong> The array contains less than 2 elements, therefore return 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Array; Bucket Sort; Radix Sort; Sorting
Python
class Solution: def maximumGap(self, nums: List[int]) -> int: n = len(nums) if n < 2: return 0 mi, mx = min(nums), max(nums) bucket_size = max(1, (mx - mi) // (n - 1)) bucket_count = (mx - mi) // bucket_size + 1 buckets = [[inf, -inf] for _ in range(bucket_count)] for v in nums: i = (v - mi) // bucket_size buckets[i][0] = min(buckets[i][0], v) buckets[i][1] = max(buckets[i][1], v) ans = 0 prev = inf for curmin, curmax in buckets: if curmin > curmax: continue ans = max(ans, curmin - prev) prev = curmax return ans
165
Compare Version Numbers
Medium
<p>Given two <strong>version strings</strong>, <code>version1</code> and <code>version2</code>, compare them. A version string consists of <strong>revisions</strong> separated by dots <code>&#39;.&#39;</code>. The <strong>value of the revision</strong> is its <strong>integer conversion</strong> ignoring leading zeros.</p> <p>To compare version strings, compare their revision values in <strong>left-to-right order</strong>. If one of the version strings has fewer revisions, treat the missing revision values as <code>0</code>.</p> <p>Return the following:</p> <ul> <li>If <code>version1 &lt; version2</code>, return -1.</li> <li>If <code>version1 &gt; version2</code>, return 1.</li> <li>Otherwise, return 0.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.2&quot;, version2 = &quot;1.10&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>version1&#39;s second revision is &quot;2&quot; and version2&#39;s second revision is &quot;10&quot;: 2 &lt; 10, so version1 &lt; version2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.01&quot;, version2 = &quot;1.001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Ignoring leading zeroes, both &quot;01&quot; and &quot;001&quot; represent the same integer &quot;1&quot;.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.0&quot;, version2 = &quot;1.0.0.0&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>version1 has less revisions, which means every missing revision are treated as &quot;0&quot;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= version1.length, version2.length &lt;= 500</code></li> <li><code>version1</code> and <code>version2</code>&nbsp;only contain digits and <code>&#39;.&#39;</code>.</li> <li><code>version1</code> and <code>version2</code>&nbsp;<strong>are valid version numbers</strong>.</li> <li>All the given revisions in&nbsp;<code>version1</code> and <code>version2</code>&nbsp;can be stored in&nbsp;a&nbsp;<strong>32-bit integer</strong>.</li> </ul>
Two Pointers; String
C++
class Solution { public: int compareVersion(string version1, string version2) { int m = version1.size(), n = version2.size(); for (int i = 0, j = 0; i < m || j < n; ++i, ++j) { int a = 0, b = 0; while (i < m && version1[i] != '.') { a = a * 10 + (version1[i++] - '0'); } while (j < n && version2[j] != '.') { b = b * 10 + (version2[j++] - '0'); } if (a != b) { return a < b ? -1 : 1; } } return 0; } };
165
Compare Version Numbers
Medium
<p>Given two <strong>version strings</strong>, <code>version1</code> and <code>version2</code>, compare them. A version string consists of <strong>revisions</strong> separated by dots <code>&#39;.&#39;</code>. The <strong>value of the revision</strong> is its <strong>integer conversion</strong> ignoring leading zeros.</p> <p>To compare version strings, compare their revision values in <strong>left-to-right order</strong>. If one of the version strings has fewer revisions, treat the missing revision values as <code>0</code>.</p> <p>Return the following:</p> <ul> <li>If <code>version1 &lt; version2</code>, return -1.</li> <li>If <code>version1 &gt; version2</code>, return 1.</li> <li>Otherwise, return 0.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.2&quot;, version2 = &quot;1.10&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>version1&#39;s second revision is &quot;2&quot; and version2&#39;s second revision is &quot;10&quot;: 2 &lt; 10, so version1 &lt; version2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.01&quot;, version2 = &quot;1.001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Ignoring leading zeroes, both &quot;01&quot; and &quot;001&quot; represent the same integer &quot;1&quot;.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.0&quot;, version2 = &quot;1.0.0.0&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>version1 has less revisions, which means every missing revision are treated as &quot;0&quot;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= version1.length, version2.length &lt;= 500</code></li> <li><code>version1</code> and <code>version2</code>&nbsp;only contain digits and <code>&#39;.&#39;</code>.</li> <li><code>version1</code> and <code>version2</code>&nbsp;<strong>are valid version numbers</strong>.</li> <li>All the given revisions in&nbsp;<code>version1</code> and <code>version2</code>&nbsp;can be stored in&nbsp;a&nbsp;<strong>32-bit integer</strong>.</li> </ul>
Two Pointers; String
C#
public class Solution { public int CompareVersion(string version1, string version2) { int m = version1.Length, n = version2.Length; for (int i = 0, j = 0; i < m || j < n; ++i, ++j) { int a = 0, b = 0; while (i < m && version1[i] != '.') { a = a * 10 + (version1[i++] - '0'); } while (j < n && version2[j] != '.') { b = b * 10 + (version2[j++] - '0'); } if (a != b) { return a < b ? -1 : 1; } } return 0; } }
165
Compare Version Numbers
Medium
<p>Given two <strong>version strings</strong>, <code>version1</code> and <code>version2</code>, compare them. A version string consists of <strong>revisions</strong> separated by dots <code>&#39;.&#39;</code>. The <strong>value of the revision</strong> is its <strong>integer conversion</strong> ignoring leading zeros.</p> <p>To compare version strings, compare their revision values in <strong>left-to-right order</strong>. If one of the version strings has fewer revisions, treat the missing revision values as <code>0</code>.</p> <p>Return the following:</p> <ul> <li>If <code>version1 &lt; version2</code>, return -1.</li> <li>If <code>version1 &gt; version2</code>, return 1.</li> <li>Otherwise, return 0.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.2&quot;, version2 = &quot;1.10&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>version1&#39;s second revision is &quot;2&quot; and version2&#39;s second revision is &quot;10&quot;: 2 &lt; 10, so version1 &lt; version2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.01&quot;, version2 = &quot;1.001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Ignoring leading zeroes, both &quot;01&quot; and &quot;001&quot; represent the same integer &quot;1&quot;.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.0&quot;, version2 = &quot;1.0.0.0&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>version1 has less revisions, which means every missing revision are treated as &quot;0&quot;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= version1.length, version2.length &lt;= 500</code></li> <li><code>version1</code> and <code>version2</code>&nbsp;only contain digits and <code>&#39;.&#39;</code>.</li> <li><code>version1</code> and <code>version2</code>&nbsp;<strong>are valid version numbers</strong>.</li> <li>All the given revisions in&nbsp;<code>version1</code> and <code>version2</code>&nbsp;can be stored in&nbsp;a&nbsp;<strong>32-bit integer</strong>.</li> </ul>
Two Pointers; String
Go
func compareVersion(version1 string, version2 string) int { m, n := len(version1), len(version2) for i, j := 0, 0; i < m || j < n; i, j = i+1, j+1 { var a, b int for i < m && version1[i] != '.' { a = a*10 + int(version1[i]-'0') i++ } for j < n && version2[j] != '.' { b = b*10 + int(version2[j]-'0') j++ } if a < b { return -1 } if a > b { return 1 } } return 0 }
165
Compare Version Numbers
Medium
<p>Given two <strong>version strings</strong>, <code>version1</code> and <code>version2</code>, compare them. A version string consists of <strong>revisions</strong> separated by dots <code>&#39;.&#39;</code>. The <strong>value of the revision</strong> is its <strong>integer conversion</strong> ignoring leading zeros.</p> <p>To compare version strings, compare their revision values in <strong>left-to-right order</strong>. If one of the version strings has fewer revisions, treat the missing revision values as <code>0</code>.</p> <p>Return the following:</p> <ul> <li>If <code>version1 &lt; version2</code>, return -1.</li> <li>If <code>version1 &gt; version2</code>, return 1.</li> <li>Otherwise, return 0.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.2&quot;, version2 = &quot;1.10&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>version1&#39;s second revision is &quot;2&quot; and version2&#39;s second revision is &quot;10&quot;: 2 &lt; 10, so version1 &lt; version2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.01&quot;, version2 = &quot;1.001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Ignoring leading zeroes, both &quot;01&quot; and &quot;001&quot; represent the same integer &quot;1&quot;.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.0&quot;, version2 = &quot;1.0.0.0&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>version1 has less revisions, which means every missing revision are treated as &quot;0&quot;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= version1.length, version2.length &lt;= 500</code></li> <li><code>version1</code> and <code>version2</code>&nbsp;only contain digits and <code>&#39;.&#39;</code>.</li> <li><code>version1</code> and <code>version2</code>&nbsp;<strong>are valid version numbers</strong>.</li> <li>All the given revisions in&nbsp;<code>version1</code> and <code>version2</code>&nbsp;can be stored in&nbsp;a&nbsp;<strong>32-bit integer</strong>.</li> </ul>
Two Pointers; String
Java
class Solution { public int compareVersion(String version1, String version2) { int m = version1.length(), n = version2.length(); for (int i = 0, j = 0; i < m || j < n; ++i, ++j) { int a = 0, b = 0; while (i < m && version1.charAt(i) != '.') { a = a * 10 + (version1.charAt(i++) - '0'); } while (j < n && version2.charAt(j) != '.') { b = b * 10 + (version2.charAt(j++) - '0'); } if (a != b) { return a < b ? -1 : 1; } } return 0; } }
165
Compare Version Numbers
Medium
<p>Given two <strong>version strings</strong>, <code>version1</code> and <code>version2</code>, compare them. A version string consists of <strong>revisions</strong> separated by dots <code>&#39;.&#39;</code>. The <strong>value of the revision</strong> is its <strong>integer conversion</strong> ignoring leading zeros.</p> <p>To compare version strings, compare their revision values in <strong>left-to-right order</strong>. If one of the version strings has fewer revisions, treat the missing revision values as <code>0</code>.</p> <p>Return the following:</p> <ul> <li>If <code>version1 &lt; version2</code>, return -1.</li> <li>If <code>version1 &gt; version2</code>, return 1.</li> <li>Otherwise, return 0.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.2&quot;, version2 = &quot;1.10&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>version1&#39;s second revision is &quot;2&quot; and version2&#39;s second revision is &quot;10&quot;: 2 &lt; 10, so version1 &lt; version2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.01&quot;, version2 = &quot;1.001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Ignoring leading zeroes, both &quot;01&quot; and &quot;001&quot; represent the same integer &quot;1&quot;.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.0&quot;, version2 = &quot;1.0.0.0&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>version1 has less revisions, which means every missing revision are treated as &quot;0&quot;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= version1.length, version2.length &lt;= 500</code></li> <li><code>version1</code> and <code>version2</code>&nbsp;only contain digits and <code>&#39;.&#39;</code>.</li> <li><code>version1</code> and <code>version2</code>&nbsp;<strong>are valid version numbers</strong>.</li> <li>All the given revisions in&nbsp;<code>version1</code> and <code>version2</code>&nbsp;can be stored in&nbsp;a&nbsp;<strong>32-bit integer</strong>.</li> </ul>
Two Pointers; String
Python
class Solution: def compareVersion(self, version1: str, version2: str) -> int: m, n = len(version1), len(version2) i = j = 0 while i < m or j < n: a = b = 0 while i < m and version1[i] != '.': a = a * 10 + int(version1[i]) i += 1 while j < n and version2[j] != '.': b = b * 10 + int(version2[j]) j += 1 if a != b: return -1 if a < b else 1 i, j = i + 1, j + 1 return 0
165
Compare Version Numbers
Medium
<p>Given two <strong>version strings</strong>, <code>version1</code> and <code>version2</code>, compare them. A version string consists of <strong>revisions</strong> separated by dots <code>&#39;.&#39;</code>. The <strong>value of the revision</strong> is its <strong>integer conversion</strong> ignoring leading zeros.</p> <p>To compare version strings, compare their revision values in <strong>left-to-right order</strong>. If one of the version strings has fewer revisions, treat the missing revision values as <code>0</code>.</p> <p>Return the following:</p> <ul> <li>If <code>version1 &lt; version2</code>, return -1.</li> <li>If <code>version1 &gt; version2</code>, return 1.</li> <li>Otherwise, return 0.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.2&quot;, version2 = &quot;1.10&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> <p><strong>Explanation:</strong></p> <p>version1&#39;s second revision is &quot;2&quot; and version2&#39;s second revision is &quot;10&quot;: 2 &lt; 10, so version1 &lt; version2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.01&quot;, version2 = &quot;1.001&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Ignoring leading zeroes, both &quot;01&quot; and &quot;001&quot; represent the same integer &quot;1&quot;.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">version1 = &quot;1.0&quot;, version2 = &quot;1.0.0.0&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>version1 has less revisions, which means every missing revision are treated as &quot;0&quot;.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= version1.length, version2.length &lt;= 500</code></li> <li><code>version1</code> and <code>version2</code>&nbsp;only contain digits and <code>&#39;.&#39;</code>.</li> <li><code>version1</code> and <code>version2</code>&nbsp;<strong>are valid version numbers</strong>.</li> <li>All the given revisions in&nbsp;<code>version1</code> and <code>version2</code>&nbsp;can be stored in&nbsp;a&nbsp;<strong>32-bit integer</strong>.</li> </ul>
Two Pointers; String
TypeScript
function compareVersion(version1: string, version2: string): number { const v1 = version1.split('.'); const v2 = version2.split('.'); for (let i = 0; i < Math.max(v1.length, v2.length); ++i) { const [n1, n2] = [+v1[i] || 0, +v2[i] || 0]; if (n1 < n2) { return -1; } if (n1 > n2) { return 1; } } return 0; }
166
Fraction to Recurring Decimal
Medium
<p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p> <p>If the fractional part is repeating, enclose the repeating part in parentheses.</p> <p>If multiple answers are possible, return <strong>any of them</strong>.</p> <p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numerator = 1, denominator = 2 <strong>Output:</strong> &quot;0.5&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numerator = 2, denominator = 1 <strong>Output:</strong> &quot;2&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numerator = 4, denominator = 333 <strong>Output:</strong> &quot;0.(012)&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li> <li><code>denominator != 0</code></li> </ul>
Hash Table; Math; String
C++
class Solution { public: string fractionToDecimal(int numerator, int denominator) { if (numerator == 0) { return "0"; } string ans; bool neg = (numerator > 0) ^ (denominator > 0); if (neg) { ans += "-"; } long long a = abs(1LL * numerator), b = abs(1LL * denominator); ans += to_string(a / b); a %= b; if (a == 0) { return ans; } ans += "."; unordered_map<long long, int> d; while (a) { d[a] = ans.size(); a *= 10; ans += to_string(a / b); a %= b; if (d.contains(a)) { ans.insert(d[a], "("); ans += ")"; break; } } return ans; } };
166
Fraction to Recurring Decimal
Medium
<p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p> <p>If the fractional part is repeating, enclose the repeating part in parentheses.</p> <p>If multiple answers are possible, return <strong>any of them</strong>.</p> <p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numerator = 1, denominator = 2 <strong>Output:</strong> &quot;0.5&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numerator = 2, denominator = 1 <strong>Output:</strong> &quot;2&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numerator = 4, denominator = 333 <strong>Output:</strong> &quot;0.(012)&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li> <li><code>denominator != 0</code></li> </ul>
Hash Table; Math; String
C#
public class Solution { public string FractionToDecimal(int numerator, int denominator) { if (numerator == 0) { return "0"; } StringBuilder sb = new StringBuilder(); bool neg = (numerator > 0) ^ (denominator > 0); sb.Append(neg ? "-" : ""); long a = Math.Abs((long)numerator), b = Math.Abs((long)denominator); sb.Append(a / b); a %= b; if (a == 0) { return sb.ToString(); } sb.Append("."); Dictionary<long, int> d = new Dictionary<long, int>(); while (a != 0) { d[a] = sb.Length; a *= 10; sb.Append(a / b); a %= b; if (d.ContainsKey(a)) { sb.Insert(d[a], "("); sb.Append(")"); break; } } return sb.ToString(); } }
166
Fraction to Recurring Decimal
Medium
<p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p> <p>If the fractional part is repeating, enclose the repeating part in parentheses.</p> <p>If multiple answers are possible, return <strong>any of them</strong>.</p> <p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numerator = 1, denominator = 2 <strong>Output:</strong> &quot;0.5&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numerator = 2, denominator = 1 <strong>Output:</strong> &quot;2&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numerator = 4, denominator = 333 <strong>Output:</strong> &quot;0.(012)&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li> <li><code>denominator != 0</code></li> </ul>
Hash Table; Math; String
Go
func fractionToDecimal(numerator int, denominator int) string { if numerator == 0 { return "0" } ans := "" if (numerator > 0) != (denominator > 0) { ans += "-" } a := int64(numerator) b := int64(denominator) a = abs(a) b = abs(b) ans += strconv.FormatInt(a/b, 10) a %= b if a == 0 { return ans } ans += "." d := make(map[int64]int) for a != 0 { if pos, ok := d[a]; ok { ans = ans[:pos] + "(" + ans[pos:] + ")" break } d[a] = len(ans) a *= 10 ans += strconv.FormatInt(a/b, 10) a %= b } return ans } func abs(x int64) int64 { if x < 0 { return -x } return x }
166
Fraction to Recurring Decimal
Medium
<p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p> <p>If the fractional part is repeating, enclose the repeating part in parentheses.</p> <p>If multiple answers are possible, return <strong>any of them</strong>.</p> <p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numerator = 1, denominator = 2 <strong>Output:</strong> &quot;0.5&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numerator = 2, denominator = 1 <strong>Output:</strong> &quot;2&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numerator = 4, denominator = 333 <strong>Output:</strong> &quot;0.(012)&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li> <li><code>denominator != 0</code></li> </ul>
Hash Table; Math; String
Java
class Solution { public String fractionToDecimal(int numerator, int denominator) { if (numerator == 0) { return "0"; } StringBuilder sb = new StringBuilder(); boolean neg = (numerator > 0) ^ (denominator > 0); sb.append(neg ? "-" : ""); long a = Math.abs((long) numerator), b = Math.abs((long) denominator); sb.append(a / b); a %= b; if (a == 0) { return sb.toString(); } sb.append("."); Map<Long, Integer> d = new HashMap<>(); while (a != 0) { d.put(a, sb.length()); a *= 10; sb.append(a / b); a %= b; if (d.containsKey(a)) { sb.insert(d.get(a), "("); sb.append(")"); break; } } return sb.toString(); } }
166
Fraction to Recurring Decimal
Medium
<p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p> <p>If the fractional part is repeating, enclose the repeating part in parentheses.</p> <p>If multiple answers are possible, return <strong>any of them</strong>.</p> <p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numerator = 1, denominator = 2 <strong>Output:</strong> &quot;0.5&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numerator = 2, denominator = 1 <strong>Output:</strong> &quot;2&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numerator = 4, denominator = 333 <strong>Output:</strong> &quot;0.(012)&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li> <li><code>denominator != 0</code></li> </ul>
Hash Table; Math; String
Python
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: if numerator == 0: return "0" ans = [] neg = (numerator > 0) ^ (denominator > 0) if neg: ans.append("-") a, b = abs(numerator), abs(denominator) ans.append(str(a // b)) a %= b if a == 0: return "".join(ans) ans.append(".") d = {} while a: d[a] = len(ans) a *= 10 ans.append(str(a // b)) a %= b if a in d: ans.insert(d[a], "(") ans.append(")") break return "".join(ans)
166
Fraction to Recurring Decimal
Medium
<p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p> <p>If the fractional part is repeating, enclose the repeating part in parentheses.</p> <p>If multiple answers are possible, return <strong>any of them</strong>.</p> <p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numerator = 1, denominator = 2 <strong>Output:</strong> &quot;0.5&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numerator = 2, denominator = 1 <strong>Output:</strong> &quot;2&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numerator = 4, denominator = 333 <strong>Output:</strong> &quot;0.(012)&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li> <li><code>denominator != 0</code></li> </ul>
Hash Table; Math; String
TypeScript
function fractionToDecimal(numerator: number, denominator: number): string { if (numerator === 0) { return '0'; } const sb: string[] = []; const neg: boolean = numerator > 0 !== denominator > 0; sb.push(neg ? '-' : ''); let a: number = Math.abs(numerator), b: number = Math.abs(denominator); sb.push(Math.floor(a / b).toString()); a %= b; if (a === 0) { return sb.join(''); } sb.push('.'); const d: Map<number, number> = new Map(); while (a !== 0) { d.set(a, sb.length); a *= 10; sb.push(Math.floor(a / b).toString()); a %= b; if (d.has(a)) { sb.splice(d.get(a)!, 0, '('); sb.push(')'); break; } } return sb.join(''); }
167
Two Sum II - Input Array Is Sorted
Medium
<p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p> <p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p> <p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p> <p>Your solution must use only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6 <strong>Output:</strong> [1,3] <strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li> <li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li> <li><code>-1000 &lt;= target &lt;= 1000</code></li> <li>The tests are generated such that there is <strong>exactly one solution</strong>.</li> </ul>
Array; Two Pointers; Binary Search
C++
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { for (int i = 0, n = numbers.size();; ++i) { int x = target - numbers[i]; int j = lower_bound(numbers.begin() + i + 1, numbers.end(), x) - numbers.begin(); if (j < n && numbers[j] == x) { return {i + 1, j + 1}; } } } };
167
Two Sum II - Input Array Is Sorted
Medium
<p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p> <p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p> <p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p> <p>Your solution must use only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6 <strong>Output:</strong> [1,3] <strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li> <li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li> <li><code>-1000 &lt;= target &lt;= 1000</code></li> <li>The tests are generated such that there is <strong>exactly one solution</strong>.</li> </ul>
Array; Two Pointers; Binary Search
Go
func twoSum(numbers []int, target int) []int { for i, n := 0, len(numbers); ; i++ { x := target - numbers[i] j := sort.SearchInts(numbers[i+1:], x) + i + 1 if j < n && numbers[j] == x { return []int{i + 1, j + 1} } } }
167
Two Sum II - Input Array Is Sorted
Medium
<p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p> <p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p> <p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p> <p>Your solution must use only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6 <strong>Output:</strong> [1,3] <strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li> <li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li> <li><code>-1000 &lt;= target &lt;= 1000</code></li> <li>The tests are generated such that there is <strong>exactly one solution</strong>.</li> </ul>
Array; Two Pointers; Binary Search
Java
class Solution { public int[] twoSum(int[] numbers, int target) { for (int i = 0, n = numbers.length;; ++i) { int x = target - numbers[i]; int l = i + 1, r = n - 1; while (l < r) { int mid = (l + r) >> 1; if (numbers[mid] >= x) { r = mid; } else { l = mid + 1; } } if (numbers[l] == x) { return new int[] {i + 1, l + 1}; } } } }
167
Two Sum II - Input Array Is Sorted
Medium
<p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p> <p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p> <p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p> <p>Your solution must use only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6 <strong>Output:</strong> [1,3] <strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li> <li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li> <li><code>-1000 &lt;= target &lt;= 1000</code></li> <li>The tests are generated such that there is <strong>exactly one solution</strong>.</li> </ul>
Array; Two Pointers; Binary Search
JavaScript
/** * @param {number[]} numbers * @param {number} target * @return {number[]} */ var twoSum = function (numbers, target) { const n = numbers.length; for (let i = 0; ; ++i) { const x = target - numbers[i]; let l = i + 1; let r = n - 1; while (l < r) { const mid = (l + r) >> 1; if (numbers[mid] >= x) { r = mid; } else { l = mid + 1; } } if (numbers[l] === x) { return [i + 1, l + 1]; } } };
167
Two Sum II - Input Array Is Sorted
Medium
<p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p> <p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p> <p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p> <p>Your solution must use only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6 <strong>Output:</strong> [1,3] <strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li> <li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li> <li><code>-1000 &lt;= target &lt;= 1000</code></li> <li>The tests are generated such that there is <strong>exactly one solution</strong>.</li> </ul>
Array; Two Pointers; Binary Search
Python
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: n = len(numbers) for i in range(n - 1): x = target - numbers[i] j = bisect_left(numbers, x, lo=i + 1) if j < n and numbers[j] == x: return [i + 1, j + 1]
167
Two Sum II - Input Array Is Sorted
Medium
<p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p> <p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p> <p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p> <p>Your solution must use only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6 <strong>Output:</strong> [1,3] <strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li> <li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li> <li><code>-1000 &lt;= target &lt;= 1000</code></li> <li>The tests are generated such that there is <strong>exactly one solution</strong>.</li> </ul>
Array; Two Pointers; Binary Search
Rust
use std::cmp::Ordering; impl Solution { pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> { let n = numbers.len(); let mut l = 0; let mut r = n - 1; loop { match (numbers[l] + numbers[r]).cmp(&target) { Ordering::Less => { l += 1; } Ordering::Greater => { r -= 1; } Ordering::Equal => { break; } } } vec![(l as i32) + 1, (r as i32) + 1] } }
167
Two Sum II - Input Array Is Sorted
Medium
<p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p> <p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p> <p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p> <p>Your solution must use only constant extra space.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6 <strong>Output:</strong> [1,3] <strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3]. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1 <strong>Output:</strong> [1,2] <strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2]. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li> <li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li> <li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li> <li><code>-1000 &lt;= target &lt;= 1000</code></li> <li>The tests are generated such that there is <strong>exactly one solution</strong>.</li> </ul>
Array; Two Pointers; Binary Search
TypeScript
function twoSum(numbers: number[], target: number): number[] { const n = numbers.length; for (let i = 0; ; ++i) { const x = target - numbers[i]; let l = i + 1; let r = n - 1; while (l < r) { const mid = (l + r) >> 1; if (numbers[mid] >= x) { r = mid; } else { l = mid + 1; } } if (numbers[l] === x) { return [i + 1, l + 1]; } } }
168
Excel Sheet Column Title
Easy
<p>Given an integer <code>columnNumber</code>, return <em>its corresponding column title as it appears in an Excel sheet</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnNumber = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnNumber = 28 <strong>Output:</strong> &quot;AB&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnNumber = 701 <strong>Output:</strong> &quot;ZY&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String
C#
public class Solution { public string ConvertToTitle(int columnNumber) { StringBuilder res = new StringBuilder(); while (columnNumber != 0) { --columnNumber; res.Append((char) ('A' + columnNumber % 26)); columnNumber /= 26; } return new string(res.ToString().Reverse().ToArray()); } }
168
Excel Sheet Column Title
Easy
<p>Given an integer <code>columnNumber</code>, return <em>its corresponding column title as it appears in an Excel sheet</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnNumber = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnNumber = 28 <strong>Output:</strong> &quot;AB&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnNumber = 701 <strong>Output:</strong> &quot;ZY&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String
Go
func convertToTitle(columnNumber int) string { res := []rune{} for columnNumber != 0 { columnNumber -= 1 res = append([]rune{rune(columnNumber%26 + int('A'))}, res...) columnNumber /= 26 } return string(res) }
168
Excel Sheet Column Title
Easy
<p>Given an integer <code>columnNumber</code>, return <em>its corresponding column title as it appears in an Excel sheet</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnNumber = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnNumber = 28 <strong>Output:</strong> &quot;AB&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnNumber = 701 <strong>Output:</strong> &quot;ZY&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String
Java
class Solution { public String convertToTitle(int columnNumber) { StringBuilder res = new StringBuilder(); while (columnNumber != 0) { --columnNumber; res.append((char) ('A' + columnNumber % 26)); columnNumber /= 26; } return res.reverse().toString(); } }
168
Excel Sheet Column Title
Easy
<p>Given an integer <code>columnNumber</code>, return <em>its corresponding column title as it appears in an Excel sheet</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnNumber = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnNumber = 28 <strong>Output:</strong> &quot;AB&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnNumber = 701 <strong>Output:</strong> &quot;ZY&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String
Python
class Solution: def convertToTitle(self, columnNumber: int) -> str: res = [] while columnNumber: columnNumber -= 1 res.append(chr(ord('A') + columnNumber % 26)) columnNumber //= 26 return ''.join(res[::-1])
168
Excel Sheet Column Title
Easy
<p>Given an integer <code>columnNumber</code>, return <em>its corresponding column title as it appears in an Excel sheet</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnNumber = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnNumber = 28 <strong>Output:</strong> &quot;AB&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnNumber = 701 <strong>Output:</strong> &quot;ZY&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String
Rust
impl Solution { #[allow(dead_code)] pub fn convert_to_title(column_number: i32) -> String { let mut ret = String::from(""); let mut column_number = column_number; while column_number > 0 { if column_number <= 26 { ret.push((('A' as u8) + (column_number as u8) - 1) as char); break; } else { let mut left = column_number % 26; left = if left == 0 { 26 } else { left }; ret.push((('A' as u8) + (left as u8) - 1) as char); column_number = (column_number - 1) / 26; } } ret.chars().rev().collect() } }
168
Excel Sheet Column Title
Easy
<p>Given an integer <code>columnNumber</code>, return <em>its corresponding column title as it appears in an Excel sheet</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnNumber = 1 <strong>Output:</strong> &quot;A&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnNumber = 28 <strong>Output:</strong> &quot;AB&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnNumber = 701 <strong>Output:</strong> &quot;ZY&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Math; String
TypeScript
function convertToTitle(columnNumber: number): string { let res: string[] = []; while (columnNumber > 0) { --columnNumber; let num: number = columnNumber % 26; res.unshift(String.fromCharCode(num + 65)); columnNumber = Math.floor(columnNumber / 26); } return res.join(''); }
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
C++
class Solution { public: int majorityElement(vector<int>& nums) { int cnt = 0, m = 0; for (int& x : nums) { if (cnt == 0) { m = x; cnt = 1; } else { cnt += m == x ? 1 : -1; } } return m; } };
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
C#
public class Solution { public int MajorityElement(int[] nums) { int cnt = 0, m = 0; foreach (int x in nums) { if (cnt == 0) { m = x; cnt = 1; } else { cnt += m == x ? 1 : -1; } } return m; } }
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
Go
func majorityElement(nums []int) int { var cnt, m int for _, x := range nums { if cnt == 0 { m, cnt = x, 1 } else { if m == x { cnt++ } else { cnt-- } } } return m }
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
Java
class Solution { public int majorityElement(int[] nums) { int cnt = 0, m = 0; for (int x : nums) { if (cnt == 0) { m = x; cnt = 1; } else { cnt += m == x ? 1 : -1; } } return m; } }
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
JavaScript
/** * @param {number[]} nums * @return {number} */ var majorityElement = function (nums) { let cnt = 0; let m = 0; for (const x of nums) { if (cnt === 0) { m = x; cnt = 1; } else { cnt += m === x ? 1 : -1; } } return m; };
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
PHP
class Solution { /** * @param Integer[] $nums * @return Integer */ function majorityElement($nums) { $m = 0; $cnt = 0; foreach ($nums as $x) { if ($cnt == 0) { $m = $x; } if ($m == $x) { $cnt++; } else { $cnt--; } } return $m; } }
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
Python
class Solution: def majorityElement(self, nums: List[int]) -> int: cnt = m = 0 for x in nums: if cnt == 0: m, cnt = x, 1 else: cnt += 1 if m == x else -1 return m
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
Rust
impl Solution { pub fn majority_element(nums: Vec<i32>) -> i32 { let mut m = 0; let mut cnt = 0; for &x in nums.iter() { if cnt == 0 { m = x; cnt = 1; } else { cnt += if m == x { 1 } else { -1 }; } } m } }
169
Majority Element
Easy
<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p> <p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> nums = [3,2,3] <strong>Output:</strong> 3 </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2] <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul> <p>&nbsp;</p> <strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?
Array; Hash Table; Divide and Conquer; Counting; Sorting
TypeScript
function majorityElement(nums: number[]): number { let cnt: number = 0; let m: number = 0; for (const x of nums) { if (cnt === 0) { m = x; cnt = 1; } else { cnt += m === x ? 1 : -1; } } return m; }
170
Two Sum III - Data structure design
Easy
<p>Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.</p> <p>Implement the <code>TwoSum</code> class:</p> <ul> <li><code>TwoSum()</code> Initializes the <code>TwoSum</code> object, with an empty array initially.</li> <li><code>void add(int number)</code> Adds <code>number</code> to the data structure.</li> <li><code>boolean find(int value)</code> Returns <code>true</code> if there exists any pair of numbers whose sum is equal to <code>value</code>, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TwoSum&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;find&quot;, &quot;find&quot;] [[], [1], [3], [5], [4], [7]] <strong>Output</strong> [null, null, null, null, true, false] <strong>Explanation</strong> TwoSum twoSum = new TwoSum(); twoSum.add(1); // [] --&gt; [1] twoSum.add(3); // [1] --&gt; [1,3] twoSum.add(5); // [1,3] --&gt; [1,3,5] twoSum.find(4); // 1 + 3 = 4, return true twoSum.find(7); // No two integers sum up to 7, return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= value &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code> and <code>find</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; Data Stream
C++
class TwoSum { public: TwoSum() { } void add(int number) { ++cnt[number]; } bool find(int value) { for (auto& [x, v] : cnt) { long y = (long) value - x; if (cnt.contains(y) && (x != y || v > 1)) { return true; } } return false; } private: unordered_map<int, int> cnt; }; /** * Your TwoSum object will be instantiated and called as such: * TwoSum* obj = new TwoSum(); * obj->add(number); * bool param_2 = obj->find(value); */
170
Two Sum III - Data structure design
Easy
<p>Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.</p> <p>Implement the <code>TwoSum</code> class:</p> <ul> <li><code>TwoSum()</code> Initializes the <code>TwoSum</code> object, with an empty array initially.</li> <li><code>void add(int number)</code> Adds <code>number</code> to the data structure.</li> <li><code>boolean find(int value)</code> Returns <code>true</code> if there exists any pair of numbers whose sum is equal to <code>value</code>, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TwoSum&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;find&quot;, &quot;find&quot;] [[], [1], [3], [5], [4], [7]] <strong>Output</strong> [null, null, null, null, true, false] <strong>Explanation</strong> TwoSum twoSum = new TwoSum(); twoSum.add(1); // [] --&gt; [1] twoSum.add(3); // [1] --&gt; [1,3] twoSum.add(5); // [1,3] --&gt; [1,3,5] twoSum.find(4); // 1 + 3 = 4, return true twoSum.find(7); // No two integers sum up to 7, return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= value &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code> and <code>find</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; Data Stream
Go
type TwoSum struct { cnt map[int]int } func Constructor() TwoSum { return TwoSum{map[int]int{}} } func (this *TwoSum) Add(number int) { this.cnt[number] += 1 } func (this *TwoSum) Find(value int) bool { for x, v := range this.cnt { y := value - x if _, ok := this.cnt[y]; ok && (x != y || v > 1) { return true } } return false } /** * Your TwoSum object will be instantiated and called as such: * obj := Constructor(); * obj.Add(number); * param_2 := obj.Find(value); */
170
Two Sum III - Data structure design
Easy
<p>Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.</p> <p>Implement the <code>TwoSum</code> class:</p> <ul> <li><code>TwoSum()</code> Initializes the <code>TwoSum</code> object, with an empty array initially.</li> <li><code>void add(int number)</code> Adds <code>number</code> to the data structure.</li> <li><code>boolean find(int value)</code> Returns <code>true</code> if there exists any pair of numbers whose sum is equal to <code>value</code>, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TwoSum&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;find&quot;, &quot;find&quot;] [[], [1], [3], [5], [4], [7]] <strong>Output</strong> [null, null, null, null, true, false] <strong>Explanation</strong> TwoSum twoSum = new TwoSum(); twoSum.add(1); // [] --&gt; [1] twoSum.add(3); // [1] --&gt; [1,3] twoSum.add(5); // [1,3] --&gt; [1,3,5] twoSum.find(4); // 1 + 3 = 4, return true twoSum.find(7); // No two integers sum up to 7, return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= value &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code> and <code>find</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; Data Stream
Java
class TwoSum { private Map<Integer, Integer> cnt = new HashMap<>(); public TwoSum() { } public void add(int number) { cnt.merge(number, 1, Integer::sum); } public boolean find(int value) { for (var e : cnt.entrySet()) { int x = e.getKey(), v = e.getValue(); int y = value - x; if (cnt.containsKey(y) && (x != y || v > 1)) { return true; } } return false; } } /** * Your TwoSum object will be instantiated and called as such: * TwoSum obj = new TwoSum(); * obj.add(number); * boolean param_2 = obj.find(value); */
170
Two Sum III - Data structure design
Easy
<p>Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.</p> <p>Implement the <code>TwoSum</code> class:</p> <ul> <li><code>TwoSum()</code> Initializes the <code>TwoSum</code> object, with an empty array initially.</li> <li><code>void add(int number)</code> Adds <code>number</code> to the data structure.</li> <li><code>boolean find(int value)</code> Returns <code>true</code> if there exists any pair of numbers whose sum is equal to <code>value</code>, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TwoSum&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;find&quot;, &quot;find&quot;] [[], [1], [3], [5], [4], [7]] <strong>Output</strong> [null, null, null, null, true, false] <strong>Explanation</strong> TwoSum twoSum = new TwoSum(); twoSum.add(1); // [] --&gt; [1] twoSum.add(3); // [1] --&gt; [1,3] twoSum.add(5); // [1,3] --&gt; [1,3,5] twoSum.find(4); // 1 + 3 = 4, return true twoSum.find(7); // No two integers sum up to 7, return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= value &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code> and <code>find</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; Data Stream
Python
class TwoSum: def __init__(self): self.cnt = defaultdict(int) def add(self, number: int) -> None: self.cnt[number] += 1 def find(self, value: int) -> bool: for x, v in self.cnt.items(): y = value - x if y in self.cnt and (x != y or v > 1): return True return False # Your TwoSum object will be instantiated and called as such: # obj = TwoSum() # obj.add(number) # param_2 = obj.find(value)
170
Two Sum III - Data structure design
Easy
<p>Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.</p> <p>Implement the <code>TwoSum</code> class:</p> <ul> <li><code>TwoSum()</code> Initializes the <code>TwoSum</code> object, with an empty array initially.</li> <li><code>void add(int number)</code> Adds <code>number</code> to the data structure.</li> <li><code>boolean find(int value)</code> Returns <code>true</code> if there exists any pair of numbers whose sum is equal to <code>value</code>, otherwise, it returns <code>false</code>.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;TwoSum&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;find&quot;, &quot;find&quot;] [[], [1], [3], [5], [4], [7]] <strong>Output</strong> [null, null, null, null, true, false] <strong>Explanation</strong> TwoSum twoSum = new TwoSum(); twoSum.add(1); // [] --&gt; [1] twoSum.add(3); // [1] --&gt; [1,3] twoSum.add(5); // [1,3] --&gt; [1,3,5] twoSum.find(4); // 1 + 3 = 4, return true twoSum.find(7); // No two integers sum up to 7, return false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-10<sup>5</sup> &lt;= number &lt;= 10<sup>5</sup></code></li> <li><code>-2<sup>31</sup> &lt;= value &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code> and <code>find</code>.</li> </ul>
Design; Array; Hash Table; Two Pointers; Data Stream
TypeScript
class TwoSum { private cnt: Map<number, number> = new Map(); constructor() {} add(number: number): void { this.cnt.set(number, (this.cnt.get(number) || 0) + 1); } find(value: number): boolean { for (const [x, v] of this.cnt) { const y = value - x; if (this.cnt.has(y) && (x !== y || v > 1)) { return true; } } return false; } } /** * Your TwoSum object will be instantiated and called as such: * var obj = new TwoSum() * obj.add(number) * var param_2 = obj.find(value) */
171
Excel Sheet Column Number
Easy
<p>Given a string <code>columnTitle</code> that represents the column title as appears in an Excel sheet, return <em>its corresponding column number</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;A&quot; <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;AB&quot; <strong>Output:</strong> 28 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;ZY&quot; <strong>Output:</strong> 701 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnTitle.length &lt;= 7</code></li> <li><code>columnTitle</code> consists only of uppercase English letters.</li> <li><code>columnTitle</code> is in the range <code>[&quot;A&quot;, &quot;FXSHRXW&quot;]</code>.</li> </ul>
Math; String
C++
class Solution { public: int titleToNumber(string columnTitle) { int ans = 0; for (char& c : columnTitle) { ans = ans * 26 + (c - 'A' + 1); } return ans; } };
171
Excel Sheet Column Number
Easy
<p>Given a string <code>columnTitle</code> that represents the column title as appears in an Excel sheet, return <em>its corresponding column number</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;A&quot; <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;AB&quot; <strong>Output:</strong> 28 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;ZY&quot; <strong>Output:</strong> 701 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnTitle.length &lt;= 7</code></li> <li><code>columnTitle</code> consists only of uppercase English letters.</li> <li><code>columnTitle</code> is in the range <code>[&quot;A&quot;, &quot;FXSHRXW&quot;]</code>.</li> </ul>
Math; String
C#
public class Solution { public int TitleToNumber(string columnTitle) { int ans = 0; foreach (char c in columnTitle) { ans = ans * 26 + c - 'A' + 1; } return ans; } }
171
Excel Sheet Column Number
Easy
<p>Given a string <code>columnTitle</code> that represents the column title as appears in an Excel sheet, return <em>its corresponding column number</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;A&quot; <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;AB&quot; <strong>Output:</strong> 28 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;ZY&quot; <strong>Output:</strong> 701 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnTitle.length &lt;= 7</code></li> <li><code>columnTitle</code> consists only of uppercase English letters.</li> <li><code>columnTitle</code> is in the range <code>[&quot;A&quot;, &quot;FXSHRXW&quot;]</code>.</li> </ul>
Math; String
Go
func titleToNumber(columnTitle string) (ans int) { for _, c := range columnTitle { ans = ans*26 + int(c-'A'+1) } return }
171
Excel Sheet Column Number
Easy
<p>Given a string <code>columnTitle</code> that represents the column title as appears in an Excel sheet, return <em>its corresponding column number</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;A&quot; <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;AB&quot; <strong>Output:</strong> 28 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;ZY&quot; <strong>Output:</strong> 701 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnTitle.length &lt;= 7</code></li> <li><code>columnTitle</code> consists only of uppercase English letters.</li> <li><code>columnTitle</code> is in the range <code>[&quot;A&quot;, &quot;FXSHRXW&quot;]</code>.</li> </ul>
Math; String
Java
class Solution { public int titleToNumber(String columnTitle) { int ans = 0; for (int i = 0; i < columnTitle.length(); ++i) { ans = ans * 26 + (columnTitle.charAt(i) - 'A' + 1); } return ans; } }
171
Excel Sheet Column Number
Easy
<p>Given a string <code>columnTitle</code> that represents the column title as appears in an Excel sheet, return <em>its corresponding column number</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;A&quot; <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;AB&quot; <strong>Output:</strong> 28 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;ZY&quot; <strong>Output:</strong> 701 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnTitle.length &lt;= 7</code></li> <li><code>columnTitle</code> consists only of uppercase English letters.</li> <li><code>columnTitle</code> is in the range <code>[&quot;A&quot;, &quot;FXSHRXW&quot;]</code>.</li> </ul>
Math; String
Python
class Solution: def titleToNumber(self, columnTitle: str) -> int: ans = 0 for c in map(ord, columnTitle): ans = ans * 26 + c - ord("A") + 1 return ans
171
Excel Sheet Column Number
Easy
<p>Given a string <code>columnTitle</code> that represents the column title as appears in an Excel sheet, return <em>its corresponding column number</em>.</p> <p>For example:</p> <pre> A -&gt; 1 B -&gt; 2 C -&gt; 3 ... Z -&gt; 26 AA -&gt; 27 AB -&gt; 28 ... </pre> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;A&quot; <strong>Output:</strong> 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;AB&quot; <strong>Output:</strong> 28 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> columnTitle = &quot;ZY&quot; <strong>Output:</strong> 701 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= columnTitle.length &lt;= 7</code></li> <li><code>columnTitle</code> consists only of uppercase English letters.</li> <li><code>columnTitle</code> is in the range <code>[&quot;A&quot;, &quot;FXSHRXW&quot;]</code>.</li> </ul>
Math; String
TypeScript
function titleToNumber(columnTitle: string): number { let ans: number = 0; for (const c of columnTitle) { ans = ans * 26 + (c.charCodeAt(0) - 'A'.charCodeAt(0) + 1); } return ans; }
172
Factorial Trailing Zeroes
Medium
<p>Given an integer <code>n</code>, return <em>the number of trailing zeroes in </em><code>n!</code>.</p> <p>Note that <code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> 3! = 6, no trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> 5! = 120, one trailing zero. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you write a solution that works in logarithmic time complexity?</p>
Math
C++
class Solution { public: int trailingZeroes(int n) { int ans = 0; while (n) { n /= 5; ans += n; } return ans; } };
172
Factorial Trailing Zeroes
Medium
<p>Given an integer <code>n</code>, return <em>the number of trailing zeroes in </em><code>n!</code>.</p> <p>Note that <code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> 3! = 6, no trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> 5! = 120, one trailing zero. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you write a solution that works in logarithmic time complexity?</p>
Math
Go
func trailingZeroes(n int) int { ans := 0 for n > 0 { n /= 5 ans += n } return ans }
172
Factorial Trailing Zeroes
Medium
<p>Given an integer <code>n</code>, return <em>the number of trailing zeroes in </em><code>n!</code>.</p> <p>Note that <code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> 3! = 6, no trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> 5! = 120, one trailing zero. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you write a solution that works in logarithmic time complexity?</p>
Math
Java
class Solution { public int trailingZeroes(int n) { int ans = 0; while (n > 0) { n /= 5; ans += n; } return ans; } }
172
Factorial Trailing Zeroes
Medium
<p>Given an integer <code>n</code>, return <em>the number of trailing zeroes in </em><code>n!</code>.</p> <p>Note that <code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> 3! = 6, no trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> 5! = 120, one trailing zero. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you write a solution that works in logarithmic time complexity?</p>
Math
Python
class Solution: def trailingZeroes(self, n: int) -> int: ans = 0 while n: n //= 5 ans += n return ans
172
Factorial Trailing Zeroes
Medium
<p>Given an integer <code>n</code>, return <em>the number of trailing zeroes in </em><code>n!</code>.</p> <p>Note that <code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 3 <strong>Output:</strong> 0 <strong>Explanation:</strong> 3! = 6, no trailing zero. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 5 <strong>Output:</strong> 1 <strong>Explanation:</strong> 5! = 120, one trailing zero. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 0 <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you write a solution that works in logarithmic time complexity?</p>
Math
TypeScript
function trailingZeroes(n: number): number { let ans = 0; while (n > 0) { n = Math.floor(n / 5); ans += n; } return ans; }
173
Binary Search Tree Iterator
Medium
<p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank">in-order traversal</a></strong> of a binary search tree (BST):</p> <ul> <li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li> <li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li> </ul> <p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p> <p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0173.Binary%20Search%20Tree%20Iterator/images/bst-tree.png" style="width: 189px; height: 178px;" /> <pre> <strong>Input</strong> [&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, 3, 7, true, 9, true, 15, true, 20, false] <strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li> </ul>
Stack; Tree; Design; Binary Search Tree; Binary Tree; Iterator
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class BSTIterator { public: vector<int> vals; int cur; BSTIterator(TreeNode* root) { cur = 0; inorder(root); } int next() { return vals[cur++]; } bool hasNext() { return cur < vals.size(); } void inorder(TreeNode* root) { if (root) { inorder(root->left); vals.push_back(root->val); inorder(root->right); } } }; /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator* obj = new BSTIterator(root); * int param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
173
Binary Search Tree Iterator
Medium
<p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank">in-order traversal</a></strong> of a binary search tree (BST):</p> <ul> <li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li> <li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li> </ul> <p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p> <p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0173.Binary%20Search%20Tree%20Iterator/images/bst-tree.png" style="width: 189px; height: 178px;" /> <pre> <strong>Input</strong> [&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, 3, 7, true, 9, true, 15, true, 20, false] <strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li> </ul>
Stack; Tree; Design; Binary Search Tree; Binary Tree; Iterator
Go
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type BSTIterator struct { stack []*TreeNode } func Constructor(root *TreeNode) BSTIterator { var stack []*TreeNode for ; root != nil; root = root.Left { stack = append(stack, root) } return BSTIterator{ stack: stack, } } func (this *BSTIterator) Next() int { cur := this.stack[len(this.stack)-1] this.stack = this.stack[:len(this.stack)-1] for node := cur.Right; node != nil; node = node.Left { this.stack = append(this.stack, node) } return cur.Val } func (this *BSTIterator) HasNext() bool { return len(this.stack) > 0 } /** * Your BSTIterator object will be instantiated and called as such: * obj := Constructor(root); * param_1 := obj.Next(); * param_2 := obj.HasNext(); */
173
Binary Search Tree Iterator
Medium
<p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank">in-order traversal</a></strong> of a binary search tree (BST):</p> <ul> <li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li> <li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li> </ul> <p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p> <p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0173.Binary%20Search%20Tree%20Iterator/images/bst-tree.png" style="width: 189px; height: 178px;" /> <pre> <strong>Input</strong> [&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, 3, 7, true, 9, true, 15, true, 20, false] <strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li> </ul>
Stack; Tree; Design; Binary Search Tree; Binary Tree; Iterator
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class BSTIterator { private int cur = 0; private List<Integer> vals = new ArrayList<>(); public BSTIterator(TreeNode root) { inorder(root); } public int next() { return vals.get(cur++); } public boolean hasNext() { return cur < vals.size(); } private void inorder(TreeNode root) { if (root != null) { inorder(root.left); vals.add(root.val); inorder(root.right); } } } /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
173
Binary Search Tree Iterator
Medium
<p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank">in-order traversal</a></strong> of a binary search tree (BST):</p> <ul> <li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li> <li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li> </ul> <p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p> <p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0173.Binary%20Search%20Tree%20Iterator/images/bst-tree.png" style="width: 189px; height: 178px;" /> <pre> <strong>Input</strong> [&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, 3, 7, true, 9, true, 15, true, 20, false] <strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li> </ul>
Stack; Tree; Design; Binary Search Tree; Binary Tree; Iterator
JavaScript
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root */ var BSTIterator = function (root) { this.stack = []; for (; root != null; root = root.left) { this.stack.push(root); } }; /** * @return {number} */ BSTIterator.prototype.next = function () { let cur = this.stack.pop(); let node = cur.right; for (; node != null; node = node.left) { this.stack.push(node); } return cur.val; }; /** * @return {boolean} */ BSTIterator.prototype.hasNext = function () { return this.stack.length > 0; }; /** * Your BSTIterator object will be instantiated and called as such: * var obj = new BSTIterator(root) * var param_1 = obj.next() * var param_2 = obj.hasNext() */
173
Binary Search Tree Iterator
Medium
<p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank">in-order traversal</a></strong> of a binary search tree (BST):</p> <ul> <li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li> <li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li> </ul> <p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p> <p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0173.Binary%20Search%20Tree%20Iterator/images/bst-tree.png" style="width: 189px; height: 178px;" /> <pre> <strong>Input</strong> [&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, 3, 7, true, 9, true, 15, true, 20, false] <strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li> </ul>
Stack; Tree; Design; Binary Search Tree; Binary Tree; Iterator
Python
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class BSTIterator: def __init__(self, root: TreeNode): def inorder(root): if root: inorder(root.left) self.vals.append(root.val) inorder(root.right) self.cur = 0 self.vals = [] inorder(root) def next(self) -> int: res = self.vals[self.cur] self.cur += 1 return res def hasNext(self) -> bool: return self.cur < len(self.vals) # Your BSTIterator object will be instantiated and called as such: # obj = BSTIterator(root) # param_1 = obj.next() # param_2 = obj.hasNext()
173
Binary Search Tree Iterator
Medium
<p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank">in-order traversal</a></strong> of a binary search tree (BST):</p> <ul> <li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li> <li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li> </ul> <p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p> <p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0173.Binary%20Search%20Tree%20Iterator/images/bst-tree.png" style="width: 189px; height: 178px;" /> <pre> <strong>Input</strong> [&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, 3, 7, true, 9, true, 15, true, 20, false] <strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li> </ul>
Stack; Tree; Design; Binary Search Tree; Binary Tree; Iterator
Rust
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } struct BSTIterator { vals: Vec<i32>, index: usize, } use std::cell::RefCell; use std::rc::Rc; /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl BSTIterator { fn inorder(root: &Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) { if let Some(node) = root { let node = node.as_ref().borrow(); Self::inorder(&node.left, res); res.push(node.val); Self::inorder(&node.right, res); } } fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self { let mut vals = vec![]; Self::inorder(&root, &mut vals); BSTIterator { vals, index: 0 } } fn next(&mut self) -> i32 { self.index += 1; self.vals[self.index - 1] } fn has_next(&self) -> bool { self.index != self.vals.len() } }
173
Binary Search Tree Iterator
Medium
<p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank">in-order traversal</a></strong> of a binary search tree (BST):</p> <ul> <li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li> <li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li> <li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li> </ul> <p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p> <p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0173.Binary%20Search%20Tree%20Iterator/images/bst-tree.png" style="width: 189px; height: 178px;" /> <pre> <strong>Input</strong> [&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;] [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []] <strong>Output</strong> [null, 3, 7, true, 9, true, 15, true, 20, false] <strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li> <li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li> <li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li> </ul>
Stack; Tree; Design; Binary Search Tree; Binary Tree; Iterator
TypeScript
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ class BSTIterator { private data: number[]; private index: number; constructor(root: TreeNode | null) { this.index = 0; this.data = []; const dfs = (root: TreeNode | null) => { if (root == null) { return; } const { val, left, right } = root; dfs(left); this.data.push(val); dfs(right); }; dfs(root); } next(): number { return this.data[this.index++]; } hasNext(): boolean { return this.index < this.data.length; } } /** * Your BSTIterator object will be instantiated and called as such: * var obj = new BSTIterator(root) * var param_1 = obj.next() * var param_2 = obj.hasNext() */
174
Dungeon Game
Hard
<p>The demons had captured the princess and imprisoned her in <strong>the bottom-right corner</strong> of a <code>dungeon</code>. The <code>dungeon</code> consists of <code>m x n</code> rooms laid out in a 2D grid. Our valiant knight was initially positioned in <strong>the top-left room</strong> and must fight his way through <code>dungeon</code> to rescue the princess.</p> <p>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</p> <p>Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight&#39;s health (represented by positive integers).</p> <p>To reach the princess as quickly as possible, the knight decides to move only <strong>rightward</strong> or <strong>downward</strong> in each step.</p> <p>Return <em>the knight&#39;s minimum initial health so that he can rescue the princess</em>.</p> <p><strong>Note</strong> that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0174.Dungeon%20Game/images/dungeon-grid-1.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dungeon = [[0]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == dungeon.length</code></li> <li><code>n == dungeon[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
C++
class Solution { public: int calculateMinimumHP(vector<vector<int>>& dungeon) { int m = dungeon.size(), n = dungeon[0].size(); int dp[m + 1][n + 1]; memset(dp, 0x3f, sizeof dp); dp[m][n - 1] = dp[m - 1][n] = 1; for (int i = m - 1; ~i; --i) { for (int j = n - 1; ~j; --j) { dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]); } } return dp[0][0]; } };
174
Dungeon Game
Hard
<p>The demons had captured the princess and imprisoned her in <strong>the bottom-right corner</strong> of a <code>dungeon</code>. The <code>dungeon</code> consists of <code>m x n</code> rooms laid out in a 2D grid. Our valiant knight was initially positioned in <strong>the top-left room</strong> and must fight his way through <code>dungeon</code> to rescue the princess.</p> <p>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</p> <p>Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight&#39;s health (represented by positive integers).</p> <p>To reach the princess as quickly as possible, the knight decides to move only <strong>rightward</strong> or <strong>downward</strong> in each step.</p> <p>Return <em>the knight&#39;s minimum initial health so that he can rescue the princess</em>.</p> <p><strong>Note</strong> that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0174.Dungeon%20Game/images/dungeon-grid-1.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dungeon = [[0]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == dungeon.length</code></li> <li><code>n == dungeon[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
C#
public class Solution { public int CalculateMinimumHP(int[][] dungeon) { int m = dungeon.Length, n = dungeon[0].Length; int[][] dp = new int[m + 1][]; for (int i = 0; i < m + 1; ++i) { dp[i] = new int[n + 1]; Array.Fill(dp[i], 1 << 30); } dp[m][n - 1] = dp[m - 1][n] = 1; for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { dp[i][j] = Math.Max(1, Math.Min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]); } } return dp[0][0]; } }
174
Dungeon Game
Hard
<p>The demons had captured the princess and imprisoned her in <strong>the bottom-right corner</strong> of a <code>dungeon</code>. The <code>dungeon</code> consists of <code>m x n</code> rooms laid out in a 2D grid. Our valiant knight was initially positioned in <strong>the top-left room</strong> and must fight his way through <code>dungeon</code> to rescue the princess.</p> <p>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</p> <p>Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight&#39;s health (represented by positive integers).</p> <p>To reach the princess as quickly as possible, the knight decides to move only <strong>rightward</strong> or <strong>downward</strong> in each step.</p> <p>Return <em>the knight&#39;s minimum initial health so that he can rescue the princess</em>.</p> <p><strong>Note</strong> that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0174.Dungeon%20Game/images/dungeon-grid-1.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dungeon = [[0]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == dungeon.length</code></li> <li><code>n == dungeon[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Go
func calculateMinimumHP(dungeon [][]int) int { m, n := len(dungeon), len(dungeon[0]) dp := make([][]int, m+1) for i := range dp { dp[i] = make([]int, n+1) for j := range dp[i] { dp[i][j] = 1 << 30 } } dp[m][n-1], dp[m-1][n] = 1, 1 for i := m - 1; i >= 0; i-- { for j := n - 1; j >= 0; j-- { dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1])-dungeon[i][j]) } } return dp[0][0] }
174
Dungeon Game
Hard
<p>The demons had captured the princess and imprisoned her in <strong>the bottom-right corner</strong> of a <code>dungeon</code>. The <code>dungeon</code> consists of <code>m x n</code> rooms laid out in a 2D grid. Our valiant knight was initially positioned in <strong>the top-left room</strong> and must fight his way through <code>dungeon</code> to rescue the princess.</p> <p>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</p> <p>Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight&#39;s health (represented by positive integers).</p> <p>To reach the princess as quickly as possible, the knight decides to move only <strong>rightward</strong> or <strong>downward</strong> in each step.</p> <p>Return <em>the knight&#39;s minimum initial health so that he can rescue the princess</em>.</p> <p><strong>Note</strong> that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0174.Dungeon%20Game/images/dungeon-grid-1.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dungeon = [[0]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == dungeon.length</code></li> <li><code>n == dungeon[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Java
class Solution { public int calculateMinimumHP(int[][] dungeon) { int m = dungeon.length, n = dungeon[0].length; int[][] dp = new int[m + 1][n + 1]; for (var e : dp) { Arrays.fill(e, 1 << 30); } dp[m][n - 1] = dp[m - 1][n] = 1; for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { dp[i][j] = Math.max(1, Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]); } } return dp[0][0]; } }
174
Dungeon Game
Hard
<p>The demons had captured the princess and imprisoned her in <strong>the bottom-right corner</strong> of a <code>dungeon</code>. The <code>dungeon</code> consists of <code>m x n</code> rooms laid out in a 2D grid. Our valiant knight was initially positioned in <strong>the top-left room</strong> and must fight his way through <code>dungeon</code> to rescue the princess.</p> <p>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</p> <p>Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight&#39;s health (represented by positive integers).</p> <p>To reach the princess as quickly as possible, the knight decides to move only <strong>rightward</strong> or <strong>downward</strong> in each step.</p> <p>Return <em>the knight&#39;s minimum initial health so that he can rescue the princess</em>.</p> <p><strong>Note</strong> that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0100-0199/0174.Dungeon%20Game/images/dungeon-grid-1.jpg" style="width: 253px; height: 253px;" /> <pre> <strong>Input:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] <strong>Output:</strong> 7 <strong>Explanation:</strong> The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> dungeon = [[0]] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>m == dungeon.length</code></li> <li><code>n == dungeon[i].length</code></li> <li><code>1 &lt;= m, n &lt;= 200</code></li> <li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li> </ul>
Array; Dynamic Programming; Matrix
Python
class Solution: def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: m, n = len(dungeon), len(dungeon[0]) dp = [[inf] * (n + 1) for _ in range(m + 1)] dp[m][n - 1] = dp[m - 1][n] = 1 for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]) return dp[0][0]
175
Combine Two Tables
Easy
<p>Table: <code>Person</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | personId | int | | lastName | varchar | | firstName | varchar | +-------------+---------+ personId is the primary key (column with unique values) for this table. This table contains information about the ID of some persons and their first and last names. </pre> <p>&nbsp;</p> <p>Table: <code>Address</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | addressId | int | | personId | int | | city | varchar | | state | varchar | +-------------+---------+ addressId is the primary key (column with unique values) for this table. Each row of this table contains information about the city and state of one person with ID = PersonId. </pre> <p>&nbsp;</p> <p>Write a solution to report the first name, last name, city, and state of each person in the <code>Person</code> table. If the address of a <code>personId</code> is not present in the <code>Address</code> table, report <code>null</code> instead.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Person table: +----------+----------+-----------+ | personId | lastName | firstName | +----------+----------+-----------+ | 1 | Wang | Allen | | 2 | Alice | Bob | +----------+----------+-----------+ Address table: +-----------+----------+---------------+------------+ | addressId | personId | city | state | +-----------+----------+---------------+------------+ | 1 | 2 | New York City | New York | | 2 | 3 | Leetcode | California | +-----------+----------+---------------+------------+ <strong>Output:</strong> +-----------+----------+---------------+----------+ | firstName | lastName | city | state | +-----------+----------+---------------+----------+ | Allen | Wang | Null | Null | | Bob | Alice | New York City | New York | +-----------+----------+---------------+----------+ <strong>Explanation:</strong> There is no address in the address table for the personId = 1 so we return null in their city and state. addressId = 1 contains information about the address of personId = 2. </pre>
Database
Python
import pandas as pd def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFrame: return pd.merge(left=person, right=address, how="left", on="personId")[ ["firstName", "lastName", "city", "state"] ]
175
Combine Two Tables
Easy
<p>Table: <code>Person</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | personId | int | | lastName | varchar | | firstName | varchar | +-------------+---------+ personId is the primary key (column with unique values) for this table. This table contains information about the ID of some persons and their first and last names. </pre> <p>&nbsp;</p> <p>Table: <code>Address</code></p> <pre> +-------------+---------+ | Column Name | Type | +-------------+---------+ | addressId | int | | personId | int | | city | varchar | | state | varchar | +-------------+---------+ addressId is the primary key (column with unique values) for this table. Each row of this table contains information about the city and state of one person with ID = PersonId. </pre> <p>&nbsp;</p> <p>Write a solution to report the first name, last name, city, and state of each person in the <code>Person</code> table. If the address of a <code>personId</code> is not present in the <code>Address</code> table, report <code>null</code> instead.</p> <p>Return the result table in <strong>any order</strong>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> Person table: +----------+----------+-----------+ | personId | lastName | firstName | +----------+----------+-----------+ | 1 | Wang | Allen | | 2 | Alice | Bob | +----------+----------+-----------+ Address table: +-----------+----------+---------------+------------+ | addressId | personId | city | state | +-----------+----------+---------------+------------+ | 1 | 2 | New York City | New York | | 2 | 3 | Leetcode | California | +-----------+----------+---------------+------------+ <strong>Output:</strong> +-----------+----------+---------------+----------+ | firstName | lastName | city | state | +-----------+----------+---------------+----------+ | Allen | Wang | Null | Null | | Bob | Alice | New York City | New York | +-----------+----------+---------------+----------+ <strong>Explanation:</strong> There is no address in the address table for the personId = 1 so we return null in their city and state. addressId = 1 contains information about the address of personId = 2. </pre>
Database
SQL
# Write your MySQL query statement below SELECT firstName, lastName, city, state FROM Person LEFT JOIN Address USING (personId);