id
int64
1
3.71k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
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...
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...
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...
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); ...
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...
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] == '*' ...
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...
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 df...
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...
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; } ...
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...
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) { ...
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...
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) ...
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...
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, ...
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...
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[...
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...
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 ...
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...
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; ...
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...
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...
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; } els...
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...
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; ...
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...
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); i...
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...
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 ...
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...
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; } ...
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...
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; } } ...
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</t...
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 ...
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</t...
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) { wh...
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</t...
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(); ...
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</t...
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</t...
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(); ...
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</t...
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 =>...
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</t...
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 ...
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</t...
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(); ...
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</t...
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...
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 ...
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 (in...
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 ...
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 ...
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 ...
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.L...
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 ...
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 ...
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(); ...
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 ...
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[...
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 ...
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; ...
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 ...
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 ...
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]] ...
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 ...
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...
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 ...
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) {...
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&quo...
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&quo...
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)...
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&quo...
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, ...
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&quo...
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&quo...
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].su...
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&quo...
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); } } } ...
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&quo...
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]) { ...
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&quo...
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&quo...
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] : ...
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&quo...
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....
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&quo...
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...
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); qs...
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...
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; ...
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...
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...
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...
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...
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...
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; ...
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...
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 = ...
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...
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]) { ...
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...
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 ...
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...
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 ...
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...
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; w...
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...
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; ...
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 solu...
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) { ...
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 solu...
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...
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 solu...
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]; ...
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 solu...
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...
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 solu...
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]; ...
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 solu...
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) { ...
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 solu...
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 =...
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 solu...
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: ...
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 solu...
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];...
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 lette...
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; di...
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 lette...
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 =...
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 lette...
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 ...
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 lette...
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 { ...
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 lette...
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 ...
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 lette...
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]; ...
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 lette...
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',...
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 lette...
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] ...
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 lette...
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 d...
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 lette...
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...
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 <c...
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] ==...
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 <c...
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] == num...
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 <c...
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 { ...
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 <c...
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]...
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 <c...
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] === num...
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 <c...
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]) { ...
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 <c...
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 + ...
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 <c...
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; } ...
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...
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* removeNthFr...
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...
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...
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...
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, ...
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...
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(ListNo...
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...
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 ...
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...
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 In...
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...
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 ...
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...
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, he...
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...
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 Solutio...
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...
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.va...
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...
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(...
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 ...
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(...
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 ...
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 == '{') { ...