id
int64
1
3.63k
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
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
Recursion; String; Dynamic Programming
C++
class Solution { public: bool isMatch(string s, string p) { int m = s.size(), n = p.size(); int f[m + 1][n + 1]; memset(f, 0, sizeof f); function<bool(int, int)> dfs = [&](int i, int j) -> bool { if (j >= n) { return i == m; } if (f[i][j]) { return f[i][j] == 1; } int res = -1; if (j + 1 < n && p[j + 1] == '*') { if (dfs(i, j + 2) or (i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j))) { res = 1; } } else if (i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j + 1)) { res = 1; } f[i][j] = res; return res == 1; }; return dfs(0, 0); } };
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
Recursion; String; Dynamic Programming
C#
public class Solution { private string s; private string p; private int m; private int n; private int[,] f; public bool IsMatch(string s, string p) { m = s.Length; n = p.Length; f = new int[m + 1, n + 1]; this.s = s; this.p = p; return dfs(0, 0); } private bool dfs(int i, int j) { if (j >= n) { return i == m; } if (f[i, j] != 0) { return f[i, j] == 1; } int res = -1; if (j + 1 < n && p[j + 1] == '*') { if (dfs(i, j + 2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i + 1, j))) { res = 1; } } else if (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i + 1, j + 1)) { res = 1; } f[i, j] = res; return res == 1; } }
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
Recursion; String; Dynamic Programming
Go
func isMatch(s string, p string) bool { m, n := len(s), len(p) f := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) } var dfs func(i, j int) bool dfs = func(i, j int) bool { if j >= n { return i == m } if f[i][j] != 0 { return f[i][j] == 1 } res := -1 if j+1 < n && p[j+1] == '*' { if dfs(i, j+2) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j)) { res = 1 } } else if i < m && (s[i] == p[j] || p[j] == '.') && dfs(i+1, j+1) { res = 1 } f[i][j] = res return res == 1 } return dfs(0, 0) }
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
Recursion; String; Dynamic Programming
Java
class Solution { private Boolean[][] f; private String s; private String p; private int m; private int n; public boolean isMatch(String s, String p) { m = s.length(); n = p.length(); f = new Boolean[m + 1][n + 1]; this.s = s; this.p = p; return dfs(0, 0); } private boolean dfs(int i, int j) { if (j >= n) { return i == m; } if (f[i][j] != null) { return f[i][j]; } boolean res = false; if (j + 1 < n && p.charAt(j + 1) == '*') { res = dfs(i, j + 2) || (i < m && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') && dfs(i + 1, j)); } else { res = i < m && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') && dfs(i + 1, j + 1); } return f[i][j] = res; } }
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
Recursion; String; Dynamic Programming
JavaScript
/** * @param {string} s * @param {string} p * @return {boolean} */ var isMatch = function (s, p) { const m = s.length; const n = p.length; const f = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); const dfs = (i, j) => { if (j >= n) { return i === m; } if (f[i][j]) { return f[i][j] === 1; } let res = -1; if (j + 1 < n && p[j + 1] === '*') { if (dfs(i, j + 2) || (i < m && (s[i] === p[j] || p[j] === '.') && dfs(i + 1, j))) { res = 1; } } else if (i < m && (s[i] === p[j] || p[j] === '.') && dfs(i + 1, j + 1)) { res = 1; } f[i][j] = res; return res === 1; }; return dfs(0, 0); };
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
Recursion; String; Dynamic Programming
PHP
class Solution { /** * @param String $s * @param String $p * @return Boolean */ function isMatch($s, $p) { $m = strlen($s); $n = strlen($p); $f = array_fill(0, $m + 1, array_fill(0, $n + 1, 0)); $dfs = function ($i, $j) use (&$s, &$p, $m, $n, &$f, &$dfs) { if ($j >= $n) { return $i == $m; } if ($f[$i][$j] != 0) { return $f[$i][$j] == 1; } $res = -1; if ($j + 1 < $n && $p[$j + 1] == '*') { if ( $dfs($i, $j + 2) || ($i < $m && ($s[$i] == $p[$j] || $p[$j] == '.') && $dfs($i + 1, $j)) ) { $res = 1; } } elseif ($i < $m && ($s[$i] == $p[$j] || $p[$j] == '.') && $dfs($i + 1, $j + 1)) { $res = 1; } $f[$i][$j] = $res; return $res == 1; }; return $dfs(0, 0); } }
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
Recursion; String; Dynamic Programming
Python
class Solution: def isMatch(self, s: str, p: str) -> bool: @cache def dfs(i, j): if j >= n: return i == m if j + 1 < n and p[j + 1] == '*': return dfs(i, j + 2) or ( i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j) ) return i < m and (s[i] == p[j] or p[j] == '.') and dfs(i + 1, j + 1) m, n = len(s), len(p) return dfs(0, 0)
10
Regular Expression Matching
Hard
<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p> <ul> <li><code>&#39;.&#39;</code> Matches any single character.​​​​</li> <li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li> </ul> <p>The matching should cover the <strong>entire</strong> input string (not partial).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot; <strong>Output:</strong> false <strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot; <strong>Output:</strong> true <strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li> <li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li> <li><code>s</code> contains only lowercase English letters.</li> <li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li> <li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li> </ul>
Recursion; String; Dynamic Programming
Rust
impl Solution { pub fn is_match(s: String, p: String) -> bool { let (m, n) = (s.len(), p.len()); let mut f = vec![vec![0; n + 1]; m + 1]; fn dfs( s: &Vec<char>, p: &Vec<char>, f: &mut Vec<Vec<i32>>, i: usize, j: usize, m: usize, n: usize, ) -> bool { if j >= n { return i == m; } if f[i][j] != 0 { return f[i][j] == 1; } let mut res = -1; if j + 1 < n && p[j + 1] == '*' { if dfs(s, p, f, i, j + 2, m, n) || (i < m && (s[i] == p[j] || p[j] == '.') && dfs(s, p, f, i + 1, j, m, n)) { res = 1; } } else if i < m && (s[i] == p[j] || p[j] == '.') && dfs(s, p, f, i + 1, j + 1, m, n) { res = 1; } f[i][j] = res; res == 1 } dfs( &s.chars().collect(), &p.chars().collect(), &mut f, 0, 0, m, n, ) } }
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
C
int min(int a, int b) { return a < b ? a : b; } int max(int a, int b) { return a > b ? a : b; } int maxArea(int* height, int heightSize) { int l = 0, r = heightSize - 1; int ans = 0; while (l < r) { int t = min(height[l], height[r]) * (r - l); ans = max(ans, t); if (height[l] < height[r]) { ++l; } else { --r; } } return ans; }
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
C++
class Solution { public: int maxArea(vector<int>& height) { int l = 0, r = height.size() - 1; int ans = 0; while (l < r) { int t = min(height[l], height[r]) * (r - l); ans = max(ans, t); if (height[l] < height[r]) { ++l; } else { --r; } } return ans; } };
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
C#
public class Solution { public int MaxArea(int[] height) { int l = 0, r = height.Length - 1; int ans = 0; while (l < r) { int t = Math.Min(height[l], height[r]) * (r - l); ans = Math.Max(ans, t); if (height[l] < height[r]) { ++l; } else { --r; } } return ans; } }
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
Go
func maxArea(height []int) (ans int) { l, r := 0, len(height)-1 for l < r { t := min(height[l], height[r]) * (r - l) ans = max(ans, t) if height[l] < height[r] { l++ } else { r-- } } return }
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
Java
class Solution { public int maxArea(int[] height) { int l = 0, r = height.length - 1; int ans = 0; while (l < r) { int t = Math.min(height[l], height[r]) * (r - l); ans = Math.max(ans, t); if (height[l] < height[r]) { ++l; } else { --r; } } return ans; } }
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
JavaScript
/** * @param {number[]} height * @return {number} */ var maxArea = function (height) { let [l, r] = [0, height.length - 1]; let ans = 0; while (l < r) { const t = Math.min(height[l], height[r]) * (r - l); ans = Math.max(ans, t); if (height[l] < height[r]) { ++l; } else { --r; } } return ans; };
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
PHP
class Solution { /** * @param Integer[] $height * @return Integer */ function maxArea($height) { $l = 0; $r = count($height) - 1; $ans = 0; while ($l < $r) { $t = min($height[$l], $height[$r]) * ($r - $l); $ans = max($ans, $t); if ($height[$l] < $height[$r]) { ++$l; } else { --$r; } } return $ans; } }
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
Python
class Solution: def maxArea(self, height: List[int]) -> int: l, r = 0, len(height) - 1 ans = 0 while l < r: t = min(height[l], height[r]) * (r - l) ans = max(ans, t) if height[l] < height[r]: l += 1 else: r -= 1 return ans
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
Rust
impl Solution { pub fn max_area(height: Vec<i32>) -> i32 { let mut l = 0; let mut r = height.len() - 1; let mut ans = 0; while l < r { ans = ans.max(height[l].min(height[r]) * ((r - l) as i32)); if height[l] < height[r] { l += 1; } else { r -= 1; } } ans } }
11
Container With Most Water
Medium
<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p> <p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p> <p>Return <em>the maximum amount of water a container can store</em>.</p> <p><strong>Notice</strong> that you may not slant the container.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0011.Container%20With%20Most%20Water/images/question_11.jpg" style="width: 600px; height: 287px;" /> <pre> <strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7] <strong>Output:</strong> 49 <strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> height = [1,1] <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == height.length</code></li> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array; Two Pointers
TypeScript
function maxArea(height: number[]): number { let [l, r] = [0, height.length - 1]; let ans = 0; while (l < r) { const t = Math.min(height[l], height[r]) * (r - l); ans = Math.max(ans, t); if (height[l] < height[r]) { ++l; } else { --r; } } return ans; }
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
C
static const char* cs[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; static const int vs[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; char* intToRoman(int num) { static char ans[20]; ans[0] = '\0'; for (int i = 0; i < 13; ++i) { while (num >= vs[i]) { num -= vs[i]; strcat(ans, cs[i]); } } return ans; }
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
C++
class Solution { public: string intToRoman(int num) { vector<string> cs = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; vector<int> vs = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; string ans; for (int i = 0; i < cs.size(); ++i) { while (num >= vs[i]) { num -= vs[i]; ans += cs[i]; } } return ans; } };
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
C#
public class Solution { public string IntToRoman(int num) { List<string> cs = new List<string>{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; List<int> vs = new List<int>{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; StringBuilder ans = new StringBuilder(); for (int i = 0; i < cs.Count; i++) { while (num >= vs[i]) { ans.Append(cs[i]); num -= vs[i]; } } return ans.ToString(); } }
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
Go
func intToRoman(num int) string { cs := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"} vs := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1} ans := &strings.Builder{} for i, v := range vs { for num >= v { num -= v ans.WriteString(cs[i]) } } return ans.String() }
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
Java
class Solution { public String intToRoman(int num) { List<String> cs = List.of("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"); List<Integer> vs = List.of(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1); StringBuilder ans = new StringBuilder(); for (int i = 0, n = cs.size(); i < n; ++i) { while (num >= vs.get(i)) { num -= vs.get(i); ans.append(cs.get(i)); } } return ans.toString(); } }
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
PHP
class Solution { /** * @param Integer $num * @return String */ function intToRoman($num) { $cs = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']; $vs = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; $ans = ''; foreach ($vs as $i => $v) { while ($num >= $v) { $num -= $v; $ans .= $cs[$i]; } } return $ans; } }
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
Python
class Solution: def intToRoman(self, num: int) -> str: cs = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I') vs = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) ans = [] for c, v in zip(cs, vs): while num >= v: num -= v ans.append(c) return ''.join(ans)
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
Rust
impl Solution { pub fn int_to_roman(num: i32) -> String { let cs = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I", ]; let vs = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; let mut num = num; let mut ans = String::new(); for (i, &v) in vs.iter().enumerate() { while num >= v { num -= v; ans.push_str(cs[i]); } } ans } }
12
Integer to Roman
Medium
<p>Seven different symbols represent Roman numerals with the following values:</p> <table> <thead> <tr> <th>Symbol</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>I</td> <td>1</td> </tr> <tr> <td>V</td> <td>5</td> </tr> <tr> <td>X</td> <td>10</td> </tr> <tr> <td>L</td> <td>50</td> </tr> <tr> <td>C</td> <td>100</td> </tr> <tr> <td>D</td> <td>500</td> </tr> <tr> <td>M</td> <td>1000</td> </tr> </tbody> </table> <p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p> <ul> <li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li> <li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li> <li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li> </ul> <p>Given an integer, convert it to a Roman numeral.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 3749</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MMMDCCXLIX&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M) 700 = DCC as 500 (D) + 100 (C) + 100 (C) 40 = XL as 10 (X) less of 50 (L) 9 = IX as 1 (I) less of 10 (X) Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places </pre> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 58</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;LVIII&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 50 = L 8 = VIII </pre> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">num = 1994</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;MCMXCIV&quot;</span></p> <p><strong>Explanation:</strong></p> <pre> 1000 = M 900 = CM 90 = XC 4 = IV </pre> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= num &lt;= 3999</code></li> </ul>
Hash Table; Math; String
TypeScript
function intToRoman(num: number): string { const cs: string[] = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']; const vs: number[] = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; const ans: string[] = []; for (let i = 0; i < vs.length; ++i) { while (num >= vs[i]) { num -= vs[i]; ans.push(cs[i]); } } return ans.join(''); }
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
C
int nums(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } int romanToInt(char* s) { int ans = nums(s[strlen(s) - 1]); for (int i = 0; i < (int) strlen(s) - 1; ++i) { int sign = nums(s[i]) < nums(s[i + 1]) ? -1 : 1; ans += sign * nums(s[i]); } return ans; }
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
C++
class Solution { public: int romanToInt(string s) { unordered_map<char, int> nums{ {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}, }; int ans = nums[s.back()]; for (int i = 0; i < s.size() - 1; ++i) { int sign = nums[s[i]] < nums[s[i + 1]] ? -1 : 1; ans += sign * nums[s[i]]; } return ans; } };
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
C#
public class Solution { public int RomanToInt(string s) { Dictionary<char, int> d = new Dictionary<char, int>(); d.Add('I', 1); d.Add('V', 5); d.Add('X', 10); d.Add('L', 50); d.Add('C', 100); d.Add('D', 500); d.Add('M', 1000); int ans = d[s[s.Length - 1]]; for (int i = 0; i < s.Length - 1; ++i) { int sign = d[s[i]] < d[s[i + 1]] ? -1 : 1; ans += sign * d[s[i]]; } return ans; } }
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
Go
func romanToInt(s string) (ans int) { d := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} for i := 0; i < len(s)-1; i++ { if d[s[i]] < d[s[i+1]] { ans -= d[s[i]] } else { ans += d[s[i]] } } ans += d[s[len(s)-1]] return }
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
Java
class Solution { public int romanToInt(String s) { String cs = "IVXLCDM"; int[] vs = {1, 5, 10, 50, 100, 500, 1000}; Map<Character, Integer> d = new HashMap<>(); for (int i = 0; i < vs.length; ++i) { d.put(cs.charAt(i), vs[i]); } int n = s.length(); int ans = d.get(s.charAt(n - 1)); for (int i = 0; i < n - 1; ++i) { int sign = d.get(s.charAt(i)) < d.get(s.charAt(i + 1)) ? -1 : 1; ans += sign * d.get(s.charAt(i)); } return ans; } }
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
JavaScript
const romanToInt = function (s) { const d = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000, }; let ans = d[s[s.length - 1]]; for (let i = 0; i < s.length - 1; ++i) { const sign = d[s[i]] < d[s[i + 1]] ? -1 : 1; ans += sign * d[s[i]]; } return ans; };
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
PHP
class Solution { /** * @param String $s * @return Integer */ function romanToInt($s) { $d = [ 'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000, ]; $ans = 0; $len = strlen($s); for ($i = 0; $i < $len - 1; $i++) { if ($d[$s[$i]] < $d[$s[$i + 1]]) { $ans -= $d[$s[$i]]; } else { $ans += $d[$s[$i]]; } } $ans += $d[$s[$len - 1]]; return $ans; } }
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
Python
class Solution: def romanToInt(self, s: str) -> int: d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} return sum((-1 if d[a] < d[b] else 1) * d[a] for a, b in pairwise(s)) + d[s[-1]]
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
Ruby
# @param {String} s # @return {Integer} def roman_to_int(s) d = { 'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000 } ans = 0 len = s.length (0...len-1).each do |i| if d[s[i]] < d[s[i + 1]] ans -= d[s[i]] else ans += d[s[i]] end end ans += d[s[len - 1]] ans end
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
Rust
impl Solution { pub fn roman_to_int(s: String) -> i32 { let d = vec![ ('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000), ] .into_iter() .collect::<std::collections::HashMap<_, _>>(); let s: Vec<char> = s.chars().collect(); let mut ans = 0; let len = s.len(); for i in 0..len - 1 { if d[&s[i]] < d[&s[i + 1]] { ans -= d[&s[i]]; } else { ans += d[&s[i]]; } } ans += d[&s[len - 1]]; ans } }
13
Roman to Integer
Easy
<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p> <pre> <strong>Symbol</strong> <strong>Value</strong> I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre> <p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p> <p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p> <ul> <li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li> <li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li> <li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li> </ul> <p>Given a roman numeral, convert it to an integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;III&quot; <strong>Output:</strong> 3 <strong>Explanation:</strong> III = 3. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;LVIII&quot; <strong>Output:</strong> 58 <strong>Explanation:</strong> L = 50, V= 5, III = 3. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;MCMXCIV&quot; <strong>Output:</strong> 1994 <strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 15</code></li> <li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li> <li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li> </ul>
Hash Table; Math; String
TypeScript
function romanToInt(s: string): number { const d: Map<string, number> = new Map([ ['I', 1], ['V', 5], ['X', 10], ['L', 50], ['C', 100], ['D', 500], ['M', 1000], ]); let ans: number = d.get(s[s.length - 1])!; for (let i = 0; i < s.length - 1; ++i) { const sign = d.get(s[i])! < d.get(s[i + 1])! ? -1 : 1; ans += sign * d.get(s[i])!; } return ans; }
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
C
char* longestCommonPrefix(char** strs, int strsSize) { for (int i = 0; strs[0][i]; i++) { for (int j = 1; j < strsSize; j++) { if (strs[j][i] != strs[0][i]) { strs[0][i] = '\0'; return strs[0]; } } } return strs[0]; }
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
C++
class Solution { public: string longestCommonPrefix(vector<string>& strs) { int n = strs.size(); for (int i = 0; i < strs[0].size(); ++i) { for (int j = 1; j < n; ++j) { if (strs[j].size() <= i || strs[j][i] != strs[0][i]) { return strs[0].substr(0, i); } } } return strs[0]; } };
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
C#
public class Solution { public string LongestCommonPrefix(string[] strs) { int n = strs.Length; for (int i = 0; i < strs[0].Length; ++i) { for (int j = 1; j < n; ++j) { if (i >= strs[j].Length || strs[j][i] != strs[0][i]) { return strs[0].Substring(0, i); } } } return strs[0]; } }
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
Go
func longestCommonPrefix(strs []string) string { n := len(strs) for i := range strs[0] { for j := 1; j < n; j++ { if len(strs[j]) <= i || strs[j][i] != strs[0][i] { return strs[0][:i] } } } return strs[0] }
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
Java
class Solution { public String longestCommonPrefix(String[] strs) { int n = strs.length; for (int i = 0; i < strs[0].length(); ++i) { for (int j = 1; j < n; ++j) { if (strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i)) { return strs[0].substring(0, i); } } } return strs[0]; } }
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
JavaScript
/** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function (strs) { for (let j = 0; j < strs[0].length; j++) { for (let i = 0; i < strs.length; i++) { if (strs[0][j] !== strs[i][j]) { return strs[0].substring(0, j); } } } return strs[0]; };
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
PHP
class Solution { /** * @param String[] $strs * @return String */ function longestCommonPrefix($strs) { $rs = ''; for ($i = 0; $i < strlen($strs[0]); $i++) { for ($j = 1; $j < count($strs); $j++) { if ($strs[0][$i] != $strs[$j][$i]) { return $rs; } } $rs = $rs . $strs[0][$i]; } return $rs; } }
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
Python
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: for i in range(len(strs[0])): for s in strs[1:]: if len(s) <= i or s[i] != strs[0][i]: return s[:i] return strs[0]
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
Ruby
# @param {String[]} strs # @return {String} def longest_common_prefix(strs) return '' if strs.nil? || strs.length.zero? return strs[0] if strs.length == 1 idx = 0 while idx < strs[0].length cur_char = strs[0][idx] str_idx = 1 while str_idx < strs.length return idx > 0 ? strs[0][0..idx-1] : '' if strs[str_idx].length <= idx return '' if strs[str_idx][idx] != cur_char && idx.zero? return strs[0][0..idx - 1] if strs[str_idx][idx] != cur_char str_idx += 1 end idx += 1 end idx > 0 ? strs[0][0..idx] : '' end
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
Rust
impl Solution { pub fn longest_common_prefix(strs: Vec<String>) -> String { let mut len = strs.iter().map(|s| s.len()).min().unwrap(); for i in (1..=len).rev() { let mut is_equal = true; let target = strs[0][0..i].to_string(); if strs.iter().all(|s| target == s[0..i]) { return target; } } String::new() } }
14
Longest Common Prefix
Easy
<p>Write a function to find the longest common prefix string amongst an array of strings.</p> <p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;] <strong>Output:</strong> &quot;fl&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;] <strong>Output:</strong> &quot;&quot; <strong>Explanation:</strong> There is no common prefix among the input strings. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= strs.length &lt;= 200</code></li> <li><code>0 &lt;= strs[i].length &lt;= 200</code></li> <li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li> </ul>
Trie; Array; String
TypeScript
function longestCommonPrefix(strs: string[]): string { const len = strs.reduce((r, s) => Math.min(r, s.length), Infinity); for (let i = len; i > 0; i--) { const target = strs[0].slice(0, i); if (strs.every(s => s.slice(0, i) === target)) { return target; } } return ''; }
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
C
int cmp(const void* a, const void* b) { return *(int*) a - *(int*) b; } int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { *returnSize = 0; int cap = 1000; int** ans = (int**) malloc(sizeof(int*) * cap); *returnColumnSizes = (int*) malloc(sizeof(int) * cap); qsort(nums, numsSize, sizeof(int), cmp); for (int i = 0; i < numsSize - 2 && nums[i] <= 0; ++i) { if (i > 0 && nums[i] == nums[i - 1]) continue; int j = i + 1, k = numsSize - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; if (sum < 0) { ++j; } else if (sum > 0) { --k; } else { if (*returnSize >= cap) { cap *= 2; ans = (int**) realloc(ans, sizeof(int*) * cap); *returnColumnSizes = (int*) realloc(*returnColumnSizes, sizeof(int) * cap); } ans[*returnSize] = (int*) malloc(sizeof(int) * 3); ans[*returnSize][0] = nums[i]; ans[*returnSize][1] = nums[j]; ans[*returnSize][2] = nums[k]; (*returnColumnSizes)[*returnSize] = 3; (*returnSize)++; ++j; --k; while (j < k && nums[j] == nums[j - 1]) ++j; while (j < k && nums[k] == nums[k + 1]) --k; } } } return ans; }
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
C++
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> ans; int n = nums.size(); for (int i = 0; i < n - 2 && nums[i] <= 0; ++i) { if (i && nums[i] == nums[i - 1]) { continue; } int j = i + 1, k = n - 1; while (j < k) { int x = nums[i] + nums[j] + nums[k]; if (x < 0) { ++j; } else if (x > 0) { --k; } else { ans.push_back({nums[i], nums[j++], nums[k--]}); while (j < k && nums[j] == nums[j - 1]) { ++j; } while (j < k && nums[k] == nums[k + 1]) { --k; } } } } return ans; } };
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
C#
public class Solution { public IList<IList<int>> ThreeSum(int[] nums) { Array.Sort(nums); int n = nums.Length; IList<IList<int>> ans = new List<IList<int>>(); for (int i = 0; i < n - 2 && nums[i] <= 0; ++i) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int j = i + 1, k = n - 1; while (j < k) { int x = nums[i] + nums[j] + nums[k]; if (x < 0) { ++j; } else if (x > 0) { --k; } else { ans.Add(new List<int> { nums[i], nums[j--], nums[k--] }); while (j < k && nums[j] == nums[j + 1]) { ++j; } while (j < k && nums[k] == nums[k + 1]) { --k; } } } } return ans; } }
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
Go
func threeSum(nums []int) (ans [][]int) { sort.Ints(nums) n := len(nums) for i := 0; i < n-2 && nums[i] <= 0; i++ { if i > 0 && nums[i] == nums[i-1] { continue } j, k := i+1, n-1 for j < k { x := nums[i] + nums[j] + nums[k] if x < 0 { j++ } else if x > 0 { k-- } else { ans = append(ans, []int{nums[i], nums[j], nums[k]}) j, k = j+1, k-1 for j < k && nums[j] == nums[j-1] { j++ } for j < k && nums[k] == nums[k+1] { k-- } } } } return }
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
Java
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> ans = new ArrayList<>(); int n = nums.length; for (int i = 0; i < n - 2 && nums[i] <= 0; ++i) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int j = i + 1, k = n - 1; while (j < k) { int x = nums[i] + nums[j] + nums[k]; if (x < 0) { ++j; } else if (x > 0) { --k; } else { ans.add(List.of(nums[i], nums[j++], nums[k--])); while (j < k && nums[j] == nums[j - 1]) { ++j; } while (j < k && nums[k] == nums[k + 1]) { --k; } } } } return ans; } }
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
JavaScript
/** * @param {number[]} nums * @return {number[][]} */ var threeSum = function (nums) { const n = nums.length; nums.sort((a, b) => a - b); const ans = []; for (let i = 0; i < n - 2 && nums[i] <= 0; ++i) { if (i > 0 && nums[i] === nums[i - 1]) { continue; } let j = i + 1; let k = n - 1; while (j < k) { const x = nums[i] + nums[j] + nums[k]; if (x < 0) { ++j; } else if (x > 0) { --k; } else { ans.push([nums[i], nums[j++], nums[k--]]); while (j < k && nums[j] === nums[j - 1]) { ++j; } while (j < k && nums[k] === nums[k + 1]) { --k; } } } } return ans; };
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
PHP
class Solution { /** * @param Integer[] $nums * @return Integer[][] */ function threeSum($nums) { sort($nums); $ans = []; $n = count($nums); for ($i = 0; $i < $n - 2 && $nums[$i] <= 0; ++$i) { if ($i > 0 && $nums[$i] == $nums[$i - 1]) { continue; } $j = $i + 1; $k = $n - 1; while ($j < $k) { $x = $nums[$i] + $nums[$j] + $nums[$k]; if ($x < 0) { ++$j; } elseif ($x > 0) { --$k; } else { $ans[] = [$nums[$i], $nums[$j++], $nums[$k--]]; while ($j < $k && $nums[$j] == $nums[$j - 1]) { ++$j; } while ($j < $k && $nums[$k] == $nums[$k + 1]) { --$k; } } } } return $ans; } }
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
Python
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() n = len(nums) ans = [] for i in range(n - 2): if nums[i] > 0: break if i and nums[i] == nums[i - 1]: continue j, k = i + 1, n - 1 while j < k: x = nums[i] + nums[j] + nums[k] if x < 0: j += 1 elif x > 0: k -= 1 else: ans.append([nums[i], nums[j], nums[k]]) j, k = j + 1, k - 1 while j < k and nums[j] == nums[j - 1]: j += 1 while j < k and nums[k] == nums[k + 1]: k -= 1 return ans
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
Ruby
# @param {Integer[]} nums # @return {Integer[][]} def three_sum(nums) res = [] nums.sort! for i in 0..(nums.length - 3) next if i > 0 && nums[i - 1] == nums[i] j = i + 1 k = nums.length - 1 while j < k do sum = nums[i] + nums[j] + nums[k] if sum < 0 j += 1 elsif sum > 0 k -= 1 else res += [[nums[i], nums[j], nums[k]]] j += 1 k -= 1 j += 1 while nums[j] == nums[j - 1] k -= 1 while nums[k] == nums[k + 1] end end end res end
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
Rust
use std::cmp::Ordering; impl Solution { pub fn three_sum(mut nums: Vec<i32>) -> Vec<Vec<i32>> { nums.sort(); let n = nums.len(); let mut res = vec![]; let mut i = 0; while i < n - 2 && nums[i] <= 0 { let mut l = i + 1; let mut r = n - 1; while l < r { match (nums[i] + nums[l] + nums[r]).cmp(&0) { Ordering::Less => { l += 1; } Ordering::Greater => { r -= 1; } Ordering::Equal => { res.push(vec![nums[i], nums[l], nums[r]]); l += 1; r -= 1; while l < n && nums[l] == nums[l - 1] { l += 1; } while r > 0 && nums[r] == nums[r + 1] { r -= 1; } } } } i += 1; while i < n - 2 && nums[i] == nums[i - 1] { i += 1; } } res } }
15
3Sum
Medium
<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p> <p>Notice that the solution set must not contain duplicate triplets.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,0,1,2,-1,-4] <strong>Output:</strong> [[-1,-1,2],[-1,0,1]] <strong>Explanation:</strong> nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,1,1] <strong>Output:</strong> [] <strong>Explanation:</strong> The only possible triplet does not sum up to 0. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0] <strong>Output:</strong> [[0,0,0]] <strong>Explanation:</strong> The only possible triplet sums up to 0. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 3000</code></li> <li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Two Pointers; Sorting
TypeScript
function threeSum(nums: number[]): number[][] { nums.sort((a, b) => a - b); const ans: number[][] = []; const n = nums.length; for (let i = 0; i < n - 2 && nums[i] <= 0; i++) { if (i > 0 && nums[i] === nums[i - 1]) { continue; } let j = i + 1; let k = n - 1; while (j < k) { const x = nums[i] + nums[j] + nums[k]; if (x < 0) { ++j; } else if (x > 0) { --k; } else { ans.push([nums[i], nums[j++], nums[k--]]); while (j < k && nums[j] === nums[j - 1]) { ++j; } while (j < k && nums[k] === nums[k + 1]) { --k; } } } } return ans; }
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
C
int cmp(const void* a, const void* b) { return (*(int*) a - *(int*) b); } int threeSumClosest(int* nums, int numsSize, int target) { qsort(nums, numsSize, sizeof(int), cmp); int ans = 1 << 30; for (int i = 0; i < numsSize; ++i) { int j = i + 1, k = numsSize - 1; while (j < k) { int t = nums[i] + nums[j] + nums[k]; if (t == target) { return t; } if (abs(t - target) < abs(ans - target)) { ans = t; } if (t > target) { --k; } else { ++j; } } } return ans; }
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
C++
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); int ans = 1 << 30; int n = nums.size(); for (int i = 0; i < n; ++i) { int j = i + 1, k = n - 1; while (j < k) { int t = nums[i] + nums[j] + nums[k]; if (t == target) return t; if (abs(t - target) < abs(ans - target)) ans = t; if (t > target) --k; else ++j; } } return ans; } };
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
C#
public class Solution { public int ThreeSumClosest(int[] nums, int target) { Array.Sort(nums); int ans = 1 << 30; int n = nums.Length; for (int i = 0; i < n; ++i) { int j = i + 1, k = n - 1; while (j < k) { int t = nums[i] + nums[j] + nums[k]; if (t == target) { return t; } if (Math.Abs(t - target) < Math.Abs(ans - target)) { ans = t; } if (t > target) { --k; } else { ++j; } } } return ans; } }
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
Go
func threeSumClosest(nums []int, target int) int { sort.Ints(nums) ans := 1 << 30 n := len(nums) for i, v := range nums { j, k := i+1, n-1 for j < k { t := v + nums[j] + nums[k] if t == target { return t } if abs(t-target) < abs(ans-target) { ans = t } if t > target { k-- } else { j++ } } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
Java
class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int ans = 1 << 30; int n = nums.length; for (int i = 0; i < n; ++i) { int j = i + 1, k = n - 1; while (j < k) { int t = nums[i] + nums[j] + nums[k]; if (t == target) { return t; } if (Math.abs(t - target) < Math.abs(ans - target)) { ans = t; } if (t > target) { --k; } else { ++j; } } } return ans; } }
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number} */ var threeSumClosest = function (nums, target) { nums.sort((a, b) => a - b); let ans = 1 << 30; const n = nums.length; for (let i = 0; i < n; ++i) { let j = i + 1; let k = n - 1; while (j < k) { const t = nums[i] + nums[j] + nums[k]; if (t === target) { return t; } if (Math.abs(t - target) < Math.abs(ans - target)) { ans = t; } if (t > target) { --k; } else { ++j; } } } return ans; };
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
PHP
class Solution { /** * @param int[] $nums * @param int $target * @return int */ function threeSumClosest($nums, $target) { $n = count($nums); $closestSum = $nums[0] + $nums[1] + $nums[2]; $minDiff = abs($closestSum - $target); sort($nums); for ($i = 0; $i < $n - 2; $i++) { $left = $i + 1; $right = $n - 1; while ($left < $right) { $sum = $nums[$i] + $nums[$left] + $nums[$right]; $diff = abs($sum - $target); if ($diff < $minDiff) { $minDiff = $diff; $closestSum = $sum; } elseif ($sum < $target) { $left++; } elseif ($sum > $target) { $right--; } else { return $sum; } } } return $closestSum; } }
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
Python
class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: nums.sort() n = len(nums) ans = inf for i, v in enumerate(nums): j, k = i + 1, n - 1 while j < k: t = v + nums[j] + nums[k] if t == target: return t if abs(t - target) < abs(ans - target): ans = t if t > target: k -= 1 else: j += 1 return ans
16
3Sum Closest
Medium
<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p> <p>Return <em>the sum of the three integers</em>.</p> <p>You may assume that each input would have exactly one solution.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [-1,2,1,-4], target = 1 <strong>Output:</strong> 2 <strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [0,0,0], target = 1 <strong>Output:</strong> 0 <strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0). </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 500</code></li> <li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li> <li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li> </ul>
Array; Two Pointers; Sorting
TypeScript
function threeSumClosest(nums: number[], target: number): number { nums.sort((a, b) => a - b); let ans: number = Infinity; const n = nums.length; for (let i = 0; i < n; ++i) { let j = i + 1; let k = n - 1; while (j < k) { const t: number = nums[i] + nums[j] + nums[k]; if (t === target) { return t; } if (Math.abs(t - target) < Math.abs(ans - target)) { ans = t; } if (t > target) { --k; } else { ++j; } } } return ans; }
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
C
char* d[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; char** letterCombinations(char* digits, int* returnSize) { if (!*digits) { *returnSize = 0; return NULL; } int size = 1; char** ans = (char**) malloc(sizeof(char*)); ans[0] = strdup(""); for (int x = 0; digits[x]; ++x) { char* s = d[digits[x] - '2']; int len = strlen(s); char** t = (char**) malloc(sizeof(char*) * size * len); int tSize = 0; for (int i = 0; i < size; ++i) { for (int j = 0; j < len; ++j) { int oldLen = strlen(ans[i]); char* tmp = (char*) malloc(oldLen + 2); strcpy(tmp, ans[i]); tmp[oldLen] = s[j]; tmp[oldLen + 1] = '\0'; t[tSize++] = tmp; } free(ans[i]); } free(ans); ans = t; size = tSize; } *returnSize = size; return ans; }
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
C++
class Solution { public: vector<string> letterCombinations(string digits) { if (digits.empty()) { return {}; } vector<string> d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> ans = {""}; for (auto& i : digits) { string s = d[i - '2']; vector<string> t; for (auto& a : ans) { for (auto& b : s) { t.push_back(a + b); } } ans = move(t); } return ans; } };
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
C#
public class Solution { public IList<string> LetterCombinations(string digits) { var ans = new List<string>(); if (digits.Length == 0) { return ans; } ans.Add(""); string[] d = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; foreach (char i in digits) { string s = d[i - '2']; var t = new List<string>(); foreach (string a in ans) { foreach (char b in s) { t.Add(a + b); } } ans = t; } return ans; } }
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
Go
func letterCombinations(digits string) []string { ans := []string{} if len(digits) == 0 { return ans } ans = append(ans, "") d := []string{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"} for _, i := range digits { s := d[i-'2'] t := []string{} for _, a := range ans { for _, b := range s { t = append(t, a+string(b)) } } ans = t } return ans }
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
Java
class Solution { public List<String> letterCombinations(String digits) { List<String> ans = new ArrayList<>(); if (digits.length() == 0) { return ans; } ans.add(""); String[] d = new String[] {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; for (char i : digits.toCharArray()) { String s = d[i - '2']; List<String> t = new ArrayList<>(); for (String a : ans) { for (String b : s.split("")) { t.add(a + b); } } ans = t; } return ans; } }
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
JavaScript
/** * @param {string} digits * @return {string[]} */ var letterCombinations = function (digits) { if (digits.length === 0) { return []; } const ans = ['']; const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; for (const i of digits) { const s = d[+i - 2]; const t = []; for (const a of ans) { for (const b of s) { t.push(a + b); } } ans.splice(0, ans.length, ...t); } return ans; };
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
PHP
class Solution { /** * @param string $digits * @return string[] */ function letterCombinations($digits) { $digitMap = [ '2' => ['a', 'b', 'c'], '3' => ['d', 'e', 'f'], '4' => ['g', 'h', 'i'], '5' => ['j', 'k', 'l'], '6' => ['m', 'n', 'o'], '7' => ['p', 'q', 'r', 's'], '8' => ['t', 'u', 'v'], '9' => ['w', 'x', 'y', 'z'], ]; $combinations = []; $this->backtrack($digits, '', 0, $digitMap, $combinations); return $combinations; } function backtrack($digits, $current, $index, $digitMap, &$combinations) { if ($index === strlen($digits)) { if ($current !== '') { $combinations[] = $current; } return; } $digit = $digits[$index]; $letters = $digitMap[$digit]; foreach ($letters as $letter) { $this->backtrack($digits, $current . $letter, $index + 1, $digitMap, $combinations); } } }
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
Python
class Solution: def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] ans = [""] for i in digits: s = d[int(i) - 2] ans = [a + b for a in ans for b in s] return ans
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
Rust
impl Solution { pub fn letter_combinations(digits: String) -> Vec<String> { let mut ans: Vec<String> = Vec::new(); if digits.is_empty() { return ans; } ans.push("".to_string()); let d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; for i in digits.chars() { let s = &d[((i as u8) - b'2') as usize]; let mut t: Vec<String> = Vec::new(); for a in &ans { for b in s.chars() { t.push(format!("{}{}", a, b)); } } ans = t; } ans } }
17
Letter Combinations of a Phone Number
Medium
<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p> <p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/images/1200px-telephone-keypad2svg.png" style="width: 300px; height: 243px;" /> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> digits = &quot;23&quot; <strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> digits = &quot;&quot; <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> digits = &quot;2&quot; <strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= digits.length &lt;= 4</code></li> <li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li> </ul>
Hash Table; String; Backtracking
TypeScript
function letterCombinations(digits: string): string[] { if (digits.length === 0) { return []; } const ans: string[] = ['']; const d = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']; for (const i of digits) { const s = d[+i - 2]; const t: string[] = []; for (const a of ans) { for (const b of s) { t.push(a + b); } } ans.splice(0, ans.length, ...t); } return ans; }
18
4Sum
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p> <ul> <li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li> <li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li> <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li> </ul> <p>You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0 <strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,2,2,2], target = 8 <strong>Output:</strong> [[2,2,2,2]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Sorting
C++
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { int n = nums.size(); vector<vector<int>> ans; if (n < 4) { return ans; } sort(nums.begin(), nums.end()); for (int i = 0; i < n - 3; ++i) { if (i && nums[i] == nums[i - 1]) { continue; } for (int j = i + 1; j < n - 2; ++j) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } int k = j + 1, l = n - 1; while (k < l) { long long x = (long long) nums[i] + nums[j] + nums[k] + nums[l]; if (x < target) { ++k; } else if (x > target) { --l; } else { ans.push_back({nums[i], nums[j], nums[k++], nums[l--]}); while (k < l && nums[k] == nums[k - 1]) { ++k; } while (k < l && nums[l] == nums[l + 1]) { --l; } } } } } return ans; } };
18
4Sum
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p> <ul> <li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li> <li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li> <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li> </ul> <p>You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0 <strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,2,2,2], target = 8 <strong>Output:</strong> [[2,2,2,2]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Sorting
C#
public class Solution { public IList<IList<int>> FourSum(int[] nums, int target) { int n = nums.Length; var ans = new List<IList<int>>(); if (n < 4) { return ans; } Array.Sort(nums); for (int i = 0; i < n - 3; ++i) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } for (int j = i + 1; j < n - 2; ++j) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } int k = j + 1, l = n - 1; while (k < l) { long x = (long) nums[i] + nums[j] + nums[k] + nums[l]; if (x < target) { ++k; } else if (x > target) { --l; } else { ans.Add(new List<int> {nums[i], nums[j], nums[k++], nums[l--]}); while (k < l && nums[k] == nums[k - 1]) { ++k; } while (k < l && nums[l] == nums[l + 1]) { --l; } } } } } return ans; } }
18
4Sum
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p> <ul> <li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li> <li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li> <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li> </ul> <p>You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0 <strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,2,2,2], target = 8 <strong>Output:</strong> [[2,2,2,2]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Sorting
Go
func fourSum(nums []int, target int) (ans [][]int) { n := len(nums) if n < 4 { return } sort.Ints(nums) for i := 0; i < n-3; i++ { if i > 0 && nums[i] == nums[i-1] { continue } for j := i + 1; j < n-2; j++ { if j > i+1 && nums[j] == nums[j-1] { continue } k, l := j+1, n-1 for k < l { x := nums[i] + nums[j] + nums[k] + nums[l] if x < target { k++ } else if x > target { l-- } else { ans = append(ans, []int{nums[i], nums[j], nums[k], nums[l]}) k++ l-- for k < l && nums[k] == nums[k-1] { k++ } for k < l && nums[l] == nums[l+1] { l-- } } } } } return }
18
4Sum
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p> <ul> <li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li> <li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li> <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li> </ul> <p>You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0 <strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,2,2,2], target = 8 <strong>Output:</strong> [[2,2,2,2]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Sorting
Java
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { int n = nums.length; List<List<Integer>> ans = new ArrayList<>(); if (n < 4) { return ans; } Arrays.sort(nums); for (int i = 0; i < n - 3; ++i) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } for (int j = i + 1; j < n - 2; ++j) { if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } int k = j + 1, l = n - 1; while (k < l) { long x = (long) nums[i] + nums[j] + nums[k] + nums[l]; if (x < target) { ++k; } else if (x > target) { --l; } else { ans.add(List.of(nums[i], nums[j], nums[k++], nums[l--])); while (k < l && nums[k] == nums[k - 1]) { ++k; } while (k < l && nums[l] == nums[l + 1]) { --l; } } } } } return ans; } }
18
4Sum
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p> <ul> <li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li> <li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li> <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li> </ul> <p>You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0 <strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,2,2,2], target = 8 <strong>Output:</strong> [[2,2,2,2]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Sorting
JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number[][]} */ var fourSum = function (nums, target) { const n = nums.length; const ans = []; if (n < 4) { return ans; } nums.sort((a, b) => a - b); for (let i = 0; i < n - 3; ++i) { if (i > 0 && nums[i] === nums[i - 1]) { continue; } for (let j = i + 1; j < n - 2; ++j) { if (j > i + 1 && nums[j] === nums[j - 1]) { continue; } let [k, l] = [j + 1, n - 1]; while (k < l) { const x = nums[i] + nums[j] + nums[k] + nums[l]; if (x < target) { ++k; } else if (x > target) { --l; } else { ans.push([nums[i], nums[j], nums[k++], nums[l--]]); while (k < l && nums[k] === nums[k - 1]) { ++k; } while (k < l && nums[l] === nums[l + 1]) { --l; } } } } } return ans; };
18
4Sum
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p> <ul> <li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li> <li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li> <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li> </ul> <p>You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0 <strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,2,2,2], target = 8 <strong>Output:</strong> [[2,2,2,2]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Sorting
PHP
class Solution { /** * @param int[] $nums * @param int $target * @return int[][] */ function fourSum($nums, $target) { $result = []; $n = count($nums); sort($nums); for ($i = 0; $i < $n - 3; $i++) { if ($i > 0 && $nums[$i] === $nums[$i - 1]) { continue; } for ($j = $i + 1; $j < $n - 2; $j++) { if ($j > $i + 1 && $nums[$j] === $nums[$j - 1]) { continue; } $left = $j + 1; $right = $n - 1; while ($left < $right) { $sum = $nums[$i] + $nums[$j] + $nums[$left] + $nums[$right]; if ($sum === $target) { $result[] = [$nums[$i], $nums[$j], $nums[$left], $nums[$right]]; while ($left < $right && $nums[$left] === $nums[$left + 1]) { $left++; } while ($left < $right && $nums[$right] === $nums[$right - 1]) { $right--; } $left++; $right--; } elseif ($sum < $target) { $left++; } else { $right--; } } } } return $result; } }
18
4Sum
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p> <ul> <li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li> <li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li> <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li> </ul> <p>You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0 <strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,2,2,2], target = 8 <strong>Output:</strong> [[2,2,2,2]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Sorting
Python
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: n = len(nums) ans = [] if n < 4: return ans nums.sort() for i in range(n - 3): if i and nums[i] == nums[i - 1]: continue for j in range(i + 1, n - 2): if j > i + 1 and nums[j] == nums[j - 1]: continue k, l = j + 1, n - 1 while k < l: x = nums[i] + nums[j] + nums[k] + nums[l] if x < target: k += 1 elif x > target: l -= 1 else: ans.append([nums[i], nums[j], nums[k], nums[l]]) k, l = k + 1, l - 1 while k < l and nums[k] == nums[k - 1]: k += 1 while k < l and nums[l] == nums[l + 1]: l -= 1 return ans
18
4Sum
Medium
<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p> <ul> <li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li> <li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li> <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li> </ul> <p>You may return the answer in <strong>any order</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0 <strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [2,2,2,2,2], target = 8 <strong>Output:</strong> [[2,2,2,2]] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 200</code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> <li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li> </ul>
Array; Two Pointers; Sorting
TypeScript
function fourSum(nums: number[], target: number): number[][] { const n = nums.length; const ans: number[][] = []; if (n < 4) { return ans; } nums.sort((a, b) => a - b); for (let i = 0; i < n - 3; ++i) { if (i > 0 && nums[i] === nums[i - 1]) { continue; } for (let j = i + 1; j < n - 2; ++j) { if (j > i + 1 && nums[j] === nums[j - 1]) { continue; } let [k, l] = [j + 1, n - 1]; while (k < l) { const x = nums[i] + nums[j] + nums[k] + nums[l]; if (x < target) { ++k; } else if (x > target) { --l; } else { ans.push([nums[i], nums[j], nums[k++], nums[l--]]); while (k < l && nums[k] === nums[k - 1]) { ++k; } while (k < l && nums[l] === nums[l + 1]) { --l; } } } } } return ans; }
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* dummy = new ListNode(0, head); ListNode* fast = dummy; ListNode* slow = dummy; while (n--) { fast = fast->next; } while (fast->next) { slow = slow->next; fast = fast->next; } slow->next = slow->next->next; return dummy->next; } };
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode RemoveNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0, head); ListNode fast = dummy, slow = dummy; while (n-- > 0) { fast = fast.next; } while (fast.next != null) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return dummy.next; } }
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func removeNthFromEnd(head *ListNode, n int) *ListNode { dummy := &ListNode{0, head} fast, slow := dummy, dummy for ; n > 0; n-- { fast = fast.Next } for fast.Next != nil { slow, fast = slow.Next, fast.Next } slow.Next = slow.Next.Next return dummy.Next }
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0, head); ListNode fast = dummy, slow = dummy; while (n-- > 0) { fast = fast.next; } while (fast.next != null) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return dummy.next; } }
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
JavaScript
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @param {number} n * @return {ListNode} */ var removeNthFromEnd = function (head, n) { const dummy = new ListNode(0, head); let fast = dummy, slow = dummy; while (n--) { fast = fast.next; } while (fast.next) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return dummy.next; };
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
PHP
/** * Definition for a singly-linked list. * class ListNode { * public $val = 0; * public $next = null; * function __construct($val = 0, $next = null) { * $this->val = $val; * $this->next = $next; * } * } */ class Solution { /** * @param ListNode $head * @param Integer $n * @return ListNode */ function removeNthFromEnd($head, $n) { $dummy = new ListNode(0, $head); $fast = $slow = $dummy; for ($i = 0; $i < $n; $i++) { $fast = $fast->next; } while ($fast->next !== null) { $fast = $fast->next; $slow = $slow->next; } $slow->next = $slow->next->next; return $dummy->next; } }
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: dummy = ListNode(next=head) fast = slow = dummy for _ in range(n): fast = fast.next while fast.next: slow, fast = slow.next, fast.next slow.next = slow.next.next return dummy.next
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
Ruby
# Definition for singly-linked list. # class ListNode # attr_accessor :val, :next # def initialize(val = 0, _next = nil) # @val = val # @next = _next # end # end # @param {ListNode} head # @param {Integer} n # @return {ListNode} def remove_nth_from_end(head, n) dummy = ListNode.new(0, head) fast = slow = dummy while n > 0 fast = fast.next n -= 1 end while fast.next slow = slow.next fast = fast.next end slow.next = slow.next.next return dummy.next end
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
Rust
// Definition for singly-linked list. // #[derive(PartialEq, Eq, Clone, Debug)] // pub struct ListNode { // pub val: i32, // pub next: Option<Box<ListNode>> // } // // impl ListNode { // #[inline] // fn new(val: i32) -> Self { // ListNode { // next: None, // val // } // } // } impl Solution { pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> { let mut dummy = Some(Box::new(ListNode { val: 0, next: head })); let mut slow = &mut dummy; let mut fast = &slow.clone(); for _ in 0..=n { fast = &fast.as_ref().unwrap().next; } while fast.is_some() { fast = &fast.as_ref().unwrap().next; slow = &mut slow.as_mut().unwrap().next; } slow.as_mut().unwrap().next = slow.as_mut().unwrap().next.as_mut().unwrap().next.take(); dummy.unwrap().next } }
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
Linked List; Two Pointers
Swift
/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init() { self.val = 0; self.next = nil; } * public init(_ val: Int) { self.val = val; self.next = nil; } * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } * } */ class Solution { func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { let dummy = ListNode(0) dummy.next = head var fast: ListNode? = dummy var slow: ListNode? = dummy for _ in 0..<n { fast = fast?.next } while fast?.next != nil { fast = fast?.next slow = slow?.next } slow?.next = slow?.next?.next return dummy.next } }
19
Remove Nth Node From End of List
Medium
<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0019.Remove%20Nth%20Node%20From%20End%20of%20List/images/remove_ex1.jpg" style="width: 542px; height: 222px;" /> <pre> <strong>Input:</strong> head = [1,2,3,4,5], n = 2 <strong>Output:</strong> [1,2,3,5] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> head = [1], n = 1 <strong>Output:</strong> [] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> head = [1,2], n = 1 <strong>Output:</strong> [1] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the list is <code>sz</code>.</li> <li><code>1 &lt;= sz &lt;= 30</code></li> <li><code>0 &lt;= Node.val &lt;= 100</code></li> <li><code>1 &lt;= n &lt;= sz</code></li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong> Could you do this in one pass?</p>
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 removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { const dummy = new ListNode(0, head); let fast = dummy; let slow = dummy; while (n--) { fast = fast.next; } while (fast.next) { slow = slow.next; fast = fast.next; } slow.next = slow.next.next; return dummy.next; }
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
C++
class Solution { public: bool isValid(string s) { string stk; for (char c : s) { if (c == '(' || c == '{' || c == '[') stk.push_back(c); else if (stk.empty() || !match(stk.back(), c)) return false; else stk.pop_back(); } return stk.empty(); } bool match(char l, char r) { return (l == '(' && r == ')') || (l == '[' && r == ']') || (l == '{' && r == '}'); } };
20
Valid Parentheses
Easy
<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p> <p>An input string is valid if:</p> <ol> <li>Open brackets must be closed by the same type of brackets.</li> <li>Open brackets must be closed in the correct order.</li> <li>Every close bracket has a corresponding open bracket of the same type.</li> </ol> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;()[]{}&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;(]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([])&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> </div> <p><strong class="example">Example 5:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;([)]&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li> </ul>
Stack; String
C#
public class Solution { public bool IsValid(string s) { Stack<char> stk = new Stack<char>(); foreach (var c in s.ToCharArray()) { if (c == '(') { stk.Push(')'); } else if (c == '[') { stk.Push(']'); } else if (c == '{') { stk.Push('}'); } else if (stk.Count == 0 || stk.Pop() != c) { return false; } } return stk.Count == 0; } }